使用httpclient下载远程文件
2016-06-21 17:21
651 查看
有些时候我们需要使用httclient直接从网络获取一个文件
httpclient底层获取文件的方式仍然是封装的流,但是使用起来会比较方便,可以设置代理等web设施
示例代码如下
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(); } }
相关文章推荐
- httpClient超时设置
- TCP协议中的三次握手四次挥手问题
- The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- 计算机网络——OSI、TCP/IP协议族详解
- 高性能网络编程
- 网络编程
- 浏览器的工作原理:新式网络浏览器幕后揭秘
- SIP与http的联系
- [Java学习] java实现http的Post、Get、代理访问请求
- Android网络请求
- 五层原理体系结构的简单分析
- 使用异步httpclient框架做get,post提交数据
- TCP/IP、Http、Socket的区别
- ASYNC_NETWORK_IO 或 NETWORK_IO
- HttpURLConnection与HttpClient区别及联系
- openstack 网络
- 启用新博客 http://taney.coding.me , 欢迎访问!
- TCP-IP 三次握手-四次挥手
- http://blog.csdn.net/mr_raptor/article/category/799879/3
- 关于ftp和http下载断点续传