【发布时间】:2020-07-01 11:22:21
【问题描述】:
使用 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 类。
方法二
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 中是否有修复,通过它我可以下载正确的文件。
【问题讨论】:
-
我已经删除了apache 标签(两次),因为这个问题不 与Apache httpd 相关。在再次编辑之前,请阅读标签的描述,其目的非常明确。
标签: java http httpclient inputstream apache-httpclient-4.x