java爬虫教程02
来源:互联网 发布:好搜排名优化软件 编辑:程序博客网 时间:2024/06/04 23:25
httpClient的response也可以手动释放连接
手动释放连接response
- CloseableHttpClient httpclient = HttpClients.createDefault();
- HttpGet httpget = new HttpGet(“http://httpbin.org/get“);
- CloseableHttpResponse response = httpclient.execute(httpget);直接执行,没有传入responseHandler
- HttpEntity entity = response.getEntity();获取数据
- InputStream instream = entity.getContent();读取数据
- finally: 释放 instream,response,httpclient;
import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;/** * This example demonstrates the recommended way of using API to make sure * the underlying connection gets released back to the connection manager. */public class ClientConnectionRelease { public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet("http://httpbin.org/"); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { byte[] data = new byte[100000]; int i = instream.read(data); System.out.println(new String(data,0,i)); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } }}
阅读全文
0 0
- java爬虫教程02
- java爬虫:Heritrix教程
- java爬虫教程01
- JAVA爬虫WebCollector教程列表
- Java 爬虫 菜逼教程 00
- java爬虫教程:模拟用户表单登录
- 分布式网络爬虫Nutch中文教程nutcher(JAVA)
- JS爬虫,Java爬虫
- python爬虫教程大全
- python爬虫教程大全
- python爬虫教程大全
- python爬虫教程大全
- 【python】爬虫教程大全
- python 爬虫教程
- python爬虫教程大全
- python爬虫教程大全
- python爬虫教程大全
- Python爬虫教程大全
- 判断某一天是一年的第几天
- 内部类
- 汽水瓶
- codeforces 822B(Crossword solving) Java
- spring HandlerExceptionResolver
- java爬虫教程02
- Android自定义UI
- java基础知识问题导航
- 面试题 7: 两个栈实现一个队列
- 消息提示-插件效果
- python3 爬虫环境准备 (三)-常用库的安装
- 获取空间hwnd
- 使用Spring StateMachine框架实现状态机
- 架构师之路(十七)Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)