使用httpclient下載遠程文件


有些時候我們需要使用httclient直接從網絡獲取一個文件
httpclient底層獲取文件的方式仍然是封裝的流,但是使用起來會比較方便,可以設置代理等web設施
示例代碼如下

CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = null;
//使用代理

if(null != proxy && StringUtils.isNotBlank(proxy.ip) && proxy.port > 0){
    HttpHost proxy = new HttpHost(proxy.ip, proxy.port);  
    config = RequestConfig.custom().setProxy(proxy).build(); 
}else{
//沒有代理,使用默認值
    config = RequestConfig.custom().build();
}
//目標文件url
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
//下載需登陸,設置登陸后的cookie
httpGet.addHeader("Cookie", cookie);

try {
    HttpResponse respone = client.execute(httpGet);
    if(respone.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
        return ;
    }
    HttpEntity entity = respone.getEntity();
    if(entity != null) {
        InputStream is = entity.getContent();
        File file = new File("目標文件生成路徑");
        FileOutputStream fos = new FileOutputStream(file); 
        byte[] buffer = new byte[4096];
        int len = -1;
        while((len = is.read(buffer) )!= -1){
            fos.write(buffer, 0, len);
        }
        fos.close();
        is.close();
        files.add(file);
    }
} catch (Exception e) {
    
}finally{
    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM