使用java.net包中的URL类。
方法一
String sourceUrl = "https://thumbor.thedailymeal.com/P09kUdGYdBReFSJne1qjVDIphDM=//https://videodam-assets.thedailymeal.com/filestore/5/3/0/2_37ec80e4c368169/5302scr_43fcce37a98877f.jpg%3Fv=2020-03-16+21%3A06%3A42&version=0";
java.net.URL url = new URL(sourceUrl);
InputStream inputStream = url.openStream();
Files.copy(inputStream, Paths.get("/Users/test/rr.png"), StandardCopyOption.REPLACE_EXISTING);
使用 Apache 的 HttpClient 类。
方法2
String sourceUrl = "https://thumbor.thedailymeal.com/P09kUdGYdBReFSJne1qjVDIphDM=//https://videodam-assets.thedailymeal.com/filestore/5/3/0/2_37ec80e4c368169/5302scr_43fcce37a98877f.jpg%3Fv=2020-03-16+21%3A06%3A42&version=0";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(sourceUrl);
HttpResponse httpresponse = httpclient.execute(httpget);
InputStream inputStream = httpresponse.getEntity().getContent();
Files.copy(inputStream, Paths.get("/Users/test/rr.png"), StandardCopyOption.REPLACE_EXISTING);
我已经使用这两种方法下载了 rr.png 文件。我发现这两个文件甚至大小也不同,并且使用方法 2 下载空白图像。我读过这两种方法是相同的,但我不明白为什么方法1下载正确的文件而方法2下载错误的文件。请澄清这一点,并让我知道方法 2 中是否有修复,以便我可以下载正确的文件。
最佳答案
第一:交叉发布:https://coderanch.com/t/728266/java/URL-openStream-HttpResponse-getEntity-getContent
第二:我猜问题是 url 以及 javas 内部类和 apache lib 如何以不同的方式处理它 - 使用调试器并单步执行它们以查看 url 真正从 tls 流中发送出去。
关于java - URL.openStream() 和 HttpResponse.getEntity().getContent() 下载Inputstream的不同文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60772183/