Android检查下载成功

时间:2012-06-22 14:16:05

标签: android http-headers httpresponse

为了下载东西我使用apache类HTTPResponse HTTPClient等。 我检查这样的有效下载:

entity.writeTo(new FileOutputStream(outfile));
        if(outfile.length()!=entity.getContentLength()){
            long fileLength = outfile.length();
            outfile.delete();
            throw new Exception("Incomplete download, "+fileLength+"/"
                    +entity.getContentLength()+" bytes downloaded");

        }

但似乎永远不会触发异常。如何妥善处理? entity.getContentLength是服务器上文件的长度还是收到的数据量?

1 个答案:

答案 0 :(得分:2)

文件请求应始终带有MD5校验和。如果您有一个MD5标头,那么您需要做的就是检查生成的MD5文件。然后你完成了,最好这样做,因为你可以有一个具有相同字节数的文件,但是一个字节在传输中会出现乱码。

        entity.writeTo(new FileOutputStream(outfile));
        String md5 = response.getHeaders("Content-MD5")[0].getValue();
        byte[] b64 = Base64.decode(md5, Base64.DEFAULT);
        String sB64 = IntegrityUtils.toASCII(b64, 0, b64.length);
        if (outfile.exists()) {
            String orgMd5 = null;
            try {
                orgMd5 = IntegrityUtils.getMD5Checksum(outfile);
            } catch (Exception e) {
                    Log.d(TAG,"Exception in file hex...");
            }
            if (orgMd5 != null && orgMd5.equals(sB64)) {
                Log.d(TAG,"MD5 is equal to files MD5");
            } else {
                Log.d(TAG,"MD5 does not equal files MD5");
            }
        }

将此课程添加到您的项目中:

public class IntegrityUtils {
public static String toASCII(byte b[], int start, int length) {
    StringBuffer asciiString = new StringBuffer();

    for (int i = start; i < (length + start); i++) {
        // exclude nulls from the ASCII representation
        if (b[i] != (byte) 0x00) {
            asciiString.append((char) b[i]);
        }
    }

    return asciiString.toString();
}

public static String getMD5Checksum(File file) throws Exception {
    byte[] b = createChecksum(file);
    String result = "";

    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}

public static byte[] createChecksum(File file) throws Exception {
    InputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;

    do {
        numRead = fis.read(buffer);
        if (numRead > 0) {
            complete.update(buffer, 0, numRead);
        }
    } while (numRead != -1);

    fis.close();
    return complete.digest();
}
}