有没有一种方法可以使用HttpURLConnection下载一个.jar文件?

huangapple go评论77阅读模式
英文:

Is there a way to download a .jar file with a httpurlconnection?

问题

服务器正在发送一个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();
}
英文:

The server is sending a jar file and i want to save it in a specific directory.
My HttpURLConnection is only reading the content of the file

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();
}

答案1

得分: 4

为什么将其解析为字符串?
也许尝试一下(https://www.baeldung.com/java-download-file)

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

Why are u parsing it as a string?
Maybe try (https://www.baeldung.com/java-download-file)

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

huangapple
  • 本文由 发表于 2020年10月17日 17:38:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64401045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定