有些時候我們需要使用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(); } }