问题
Using URL class in java.net package.
Method 1
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);
Using Apache's HttpClient class.
Method 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);
I have downloaded the rr.png file using both the methods. I found both the files are different even in sizes also and using method 2 download a blank image. I have read both the methods are same but I do not understand why method1 downloading correct file and method2 downloading wrong file. Please clarify this and also let me know if there is a fix in the method 2 through which I can download the correct file.
回答1:
First: cross-posting: https://coderanch.com/t/728266/java/URL-openStream-HttpResponse-getEntity-getContent
Second: I guess the issue is the url and how it's handled differently by javas internal class and apache lib - use a debugger and step through them to see what url really gets send out the tls stream.
来源:https://stackoverflow.com/questions/60772183/url-openstream-and-httpresponse-getentity-getcontent-downloading-different