apache 如何在FileUtils.copyURLToFile(URL,File)方法中指定用户代理和引用者?

rbl8hiat  于 2022-11-25  发布在  Apache
关注(0)|答案(3)|浏览(122)

我正在使用Apache Commons IO 2.4部件**FileUtils.copyURLToFile(URL, File)**下载文件并将其保存到我的计算机上。问题是有些站点拒绝在没有引用和用户代理数据的情况下连接。
我的疑问:
1.有没有办法指定copyURLToFile方法的用户代理和引用者?
1.或者我应该使用另一种方法来下载文件,然后将给定的InputStream保存到文件中?

fzwojiic

fzwojiic1#

我用HttpComponents代替了Commons-IO重新实现了这个功能。

  • 最终代码:*
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值,这对许多Web站点都很重要。

ehxuflar

ehxuflar2#

完成有关如何处理超时的已接受答案:
如果要设置超时,则必须创建如下CloseableHttpClient

RequestConfig config = RequestConfig.custom()
                 .setConnectTimeout(connectionTimeout)
                 .setConnectionRequestTimeout(readDataTimeout)
                 .setSocketTimeout(readDataTimeout)
                 .build();

CloseableHttpClient httpClient = HttpClientBuilder
                 .create()
                 .setDefaultRequestConfig(config)
                 .build();

而且,使用try-with-resource语句来处理CloseableHttpClient的结束语句来创建CloseableHttpClient可能是一个好主意:

try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
  ... rest of the code using httpClient
}
fhity93d

fhity93d3#

可能不会,除非您能够掌握打开URL的底层机制。
我推荐使用https://hc.apache.org/库。它有很多关于头文件等的特性。

相关问题