【问题标题】:Is there a way to download a .jar file with a httpurlconnection?有没有办法下载带有 httpurlconnection 的 .jar 文件?
【发布时间】:2020-10-17 09:38:09
【问题描述】:

服务器正在发送一个 jar 文件,我想将它保存在特定目录中。 我的 HttpURLConnection 只是读取文件的内容

public static String update(String url, String version) throws MalformedURLException, IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        
    return readResponse(con.getInputStream());
}
private static String readResponse(InputStream in){
    BufferedReader br = new BufferedReader(new InputStreamReader((in)));
    StringBuilder sb = new StringBuilder();
    String output;
    while ((output = br.readLine()) != null) {
        sb.append(output);
    }
    return sb.toString();
}

【问题讨论】:

  • JAR 文件不是文本,也不包含行。您应该使用InputSream,而不是Reader,当然也不是readLine()String

标签: java httpurlconnection


【解决方案1】:

你为什么要把它解析成一个字符串? 也许试试 (https://www.baeldung.com/java-download-file)

InputStream in = new URL(FILE_URL).openStream();
Files.copy(in, Paths.get(FILE_NAME), StandardCopyOption.REPLACE_EXISTING);

【讨论】:

  • 注意:这段代码会泄漏内存,它需要try-with-resources。
猜你喜欢
  • 2023-02-07
  • 2023-03-30
  • 1970-01-01
  • 2018-12-17
  • 2021-03-14
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
相关资源
最近更新 更多