使用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(); } }