Mik*_* B. 3 java apache apache-commons http-headers
我使用FileUtils.copyURLToFile(URL, File),一个Apache的百科全书IO 2.4的一部分,下载并保存在我的电脑上的文件。问题是某些站点拒绝了没有引荐来源网址和用户代理数据的连接。
我的问题:
copyURLToFile方法的用户代理和引荐来源?InputStream文件保存到文件?我用HttpComponents代替来重新实现了功能Commons-IO。该代码允许您根据URL下载Java文件并将其保存在特定的目标位置。
最终代码:
public static boolean saveFile(URL imgURL, String imgSavePath) {
boolean isSucceed = true;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(imgURL.toString());
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.11 Safari/537.36");
httpGet.addHeader("Referer", "https://www.google.com");
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity imageEntity = httpResponse.getEntity();
if (imageEntity != null) {
FileUtils.copyInputStreamToFile(imageEntity.getContent(), new File(imgSavePath));
}
} catch (IOException e) {
isSucceed = false;
}
httpGet.releaseConnection();
return isSucceed;
}
Run Code Online (Sandbox Code Playgroud)
当然,上面的代码比一行代码占用更多的空间:
FileUtils.copyURLToFile(imgURL, new File(imgSavePath),
URLS_FETCH_TIMEOUT, URLS_FETCH_TIMEOUT);
Run Code Online (Sandbox Code Playgroud)
但它会给你更多的控制权的过程,让你不仅指定超时,但User-Agent和Referer值,这对于许多Web站点的关键。
| 归档时间: |
|
| 查看次数: |
1813 次 |
| 最近记录: |