Java http 下载损坏文件

标签 java http download

我有一个问题,我似乎无法解决... 我对文件进行了 http 下载,但服务器和客户端上的文件的 CRC32 不匹配。此外,文件大小不同,所以显然我一定是做错了什么……当我通过 Firefox 下载时,文件大小没问题……所以我猜它在客户端代码中的某个地方。

我已经找到了Corrupt file when using Java to download file ,但这对我也没有帮助...

代码如下:

private void downloadJar(String fileName, long crc32Server) throws IOException {
  System.out.println("Downloading file '" + fileName + "' from server '" + mServer + "'.");
  HttpURLConnection sourceConnection = null;
  BufferedInputStream inputStream = null;
  BufferedWriter fileWriter = null;
  long crc32Client;
  try {
    URL sourceURL = new URL(fileName);
    try {
      sourceConnection = (HttpURLConnection)sourceURL.openConnection();
    }
    catch (MalformedURLException exc) {
      throw new RuntimeException("Configured URL caused a MalformedURLException: ", exc);
    }
    sourceConnection.setRequestProperty("Accept-Encoding", "zip, jar");
    sourceConnection.connect();
    inputStream = new BufferedInputStream(sourceConnection.getInputStream());
    fileWriter = new BufferedWriter(new FileWriter(targetFolder + File.separator + fileName));
    CRC32 crc32 = new CRC32();
    for (int singleByte = inputStream.read(); singleByte != -1; singleByte = inputStream.read()) {
      fileWriter.write(singleByte);
      crc32.update(singleByte);
    }
    crc32Client = crc32.getValue();
  }
  finally {
    if (inputStream != null) {
      inputStream.close();
    }
    if (fileWriter != null) {
      fileWriter.flush();
      fileWriter.close();
    }
    if (sourceConnection != null) {
      sourceConnection.disconnect();
    }
  }
  if (crc32Client != crc32Server) {
    //      deleteFile(fileName);
    throw new IOException("CRC32 did not match for file '" + fileName + "': " + crc32Client + "!="
        + crc32Server);
  }
}

最佳答案

你应该使用 BufferedOutputStream而不是 FileWriter/BufferedWriter .一般来说,*Streams 处理原始二进制数据,而 *Writers 处理字符数据(这是对给定字符编码的原始二进制数据的解释)。

关于Java http 下载损坏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/487632/

相关文章:

java - 无法将 JSON 对象发送到 Rest Web 服务

java - Java 类的 Groovy Spock 测试 - 如何模拟 Clob

python - 我想使用 LADS DAAC 站点中提供的 Python 脚本从 HTTP 站点下载 MODIS 数据。但是在运行脚本时出现错误

http - 如何在 Erlang 中读取 http POST 请求的正文

c# - 使用 Selenium 保存页面中的图像

java - 如何在 Apache camel 中使用 POST 调用 REST?

java - 异常:ClassNotFoundException & NoClassDefFoundError At Release Run Application

http - 使用 Clack/ningle 在 Web 服务器中嵌入图像

android - 如何在下载 .mp4 视频时更新进度条?

security - 使用正确的文件名在浏览器中安全下载文件