gpt4 book ai didi

java - 如何在 FileUtils.copyURLToFile(URL, File) 方法中指定 User Agent 和 Referer?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:11 26 4
gpt4 key购买 nike

我正在使用 FileUtils.copyURLToFile(URL, File) ,一个Apache Commons IO 2.4部分,将文件下载并保存在我的电脑上。问题是一些网站在没有推荐人和用户代理数据的情况下拒绝连接。

我的问题:

  1. 有什么方法可以指定用户代理和引荐来源网址到 copyURLToFile 方法吗?

  2. 或者我应该使用另一种方法来下载文件,然后将给定的 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;
}

当然,上面的代码比单行代码占用更多的空间:

FileUtils.copyURLToFile(imgURL, new File(imgSavePath),
URLS_FETCH_TIMEOUT, URLS_FETCH_TIMEOUT);

但它会让您更好地控制流程,让您不仅可以指定超时,还可以指定 User-AgentReferer 值,这对许多网站来说都是至关重要的.

关于java - 如何在 FileUtils.copyURLToFile(URL, File) 方法中指定 User Agent 和 Referer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35995431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com