【问题标题】:Android check download successful安卓检查下载成功
【发布时间】:2012-06-22 14:16:04
【问题描述】:

为了下载东西,我使用 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 是服务器上文件的长度还是接收到的数据量?

【问题讨论】:

标签: android http-headers httpresponse


【解决方案1】:

文件请求应始终带有 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();
}
}

【讨论】:

  • 遗憾的是,据我所知,很少有服务器会发送 md5 标头。我要求我的网站管理员将其添加到配置中。更多测试指出,在我的情况下,entity.getContentLength 返回与 response.getHeaders("Content-Length") 相同。我会接受这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 2016-07-08
  • 2012-02-25
相关资源
最近更新 更多