httpclient总结
1、httpclient总结:
一、基本知识准备
(1)构建URI工具类,URIBuilder
(2)HttpResponse类,可以添加Header信息
获取所有Header信息的方法,调用HeaderIterator接口
HeaderIterator it = response.headerIterator("Set-Cookie");
while (it.hasNext()) {
System.out.println(it.next());
}
(3)HttpEntity内容实体 可以被装入Request和Response中..
只有独立的entity才可以被重复调用.
当请求需要entity HttpEntity.writeTo(OutputStream)
从响应中解析entity HttpEntity.getContent()
HttpEntity.getContentType()
HttpEntity.getContentLength()
HttpEntity.getContentEncoding()
对entity进行解析可采用流的方式或者调用EntityUtils,但后者有长度的限制2048
利用 BufferedEntity可以将entity缓存到本地磁盘,用来进行多次读取.
创建entity信息时需要指定meta信息,包括contentType
(4)可以调用ResponseHandler写入响应统一处理
二、常用策略
keep-Alieve策略:自定义ConnectionKeepAliveStrategy
重定向策略:LaxRedirectStrategy
三、资源分配
当CloseableHttpClient不再需要,并且不再连接管理的范围,需要调用CloseableHttpClient.close()方法将其关闭..
四、HttpClient状态管理
1、在HTTP上下文中,很多有逻辑关系的请求都可以放入到同一个session中..
HttpClient本身线程HttpContext 包含任意的键值对,因此线程不安全..通常建议每个线程拥有自己的上下文
2、自动恢复机制---->HttpRequestRetryHandler
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception,int executionCount,HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
CloseableHttpClient httpclient = HttpClients.custom()
.setRetryHandler(myRetryHandler)
.build();
4、多线程中的应用AtomicInteger,,,,待研究...
从连接管理器中获取连接
(1)通过HttpClientConnectionManager来管理一个连接
HttpClientContext context = HttpClientContext.create();
HttpClientConnectionManager connMrg = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("www.yeetrack.com", 80));
// 获取新的连接. 这里可能耗费很多时间
ConnectionRequest connRequest = connMrg.requestConnection(route, null);
// 10秒超时
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
try {
// 如果创建连接失败
if (!conn.isOpen()) {
// establish connection based on its route info
connMrg.connect(conn, route, 1000, context);
// and mark it as route complete
connMrg.routeComplete(conn, route, context);
}
// 进行自己的操作.
} finally {
connMrg.releaseConnection(conn, null, 1, TimeUnit.MINUTES);
}
通过更复杂的PoolingHttpClientConnectionManager来管理多个连接,适合多线程中的请求
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// 将最大连接数增加到200
cm.setMaxTotal(200);
// 将每个路由基础的连接增加到20
cm.setDefaultMaxPerRoute(20);
//将目标主机的最大连接数增加到50
HttpHost localhost = new HttpHost("www.yeetrack.com", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50); CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
示例1---------------------------------
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build(); // URL列表数组
String[] urisToGet = {
"http://www.domain1.com/",
"http://www.domain2.com/",
"http://www.domain3.com/",
"http://www.domain4.com/"
}; // 为每个url创建一个线程,GetThread是自定义的类
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
} // 启动线程
for (int j = 0; j < threads.length; j++) {
threads[j].start();
} // join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
自定义类GetThread
static class GetThread extends Thread { private final CloseableHttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget; public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {
this.httpClient = httpClient;
this.context = HttpClientContext.create();
this.httpget = httpget;
} @Override
public void run() {
try {
CloseableHttpResponse response = httpClient.execute(
httpget, context);
try {
HttpEntity entity = response.getEntity();
} finally {
response.close();
}
} catch (ClientProtocolException ex) {
// Handle protocol errors
} catch (IOException ex) {
// Handle I/O errors
}
} }
注意:即使httpclient可以被多线程访问,仍建议每个httpclient采用自己的context
5、 public static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
// 可选的, 关闭30秒内不活动的连接
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
httpclient总结的更多相关文章
- HttpClient的替代者 - RestTemplate
需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...
- 关于微软HttpClient使用,避免踩坑
最近公司对于WebApi的场景使用也越来越加大了,随之而来就是Api的客户端工具我们使用哪个?我们最常用的估计就是HttpClient,在微软类库中命名空间地址:System.Net.Http,是一个 ...
- 使用HttpClient的优解
新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...
- Java的异步HttpClient
上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...
- 揭秘Windows10 UWP中的httpclient接口[2]
阅读目录: 概述 如何选择 System.Net.Http Windows.Web.Http HTTP的常用功能 修改http头部 设置超时 使用身份验证凭据 使用客户端证书 cookie处理 概述 ...
- C#中HttpClient使用注意:预热与长连接
最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...
- HttpClient调用webApi时注意的小问题
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...
- HttpClient相关
HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...
- Atitit.http httpclient实践java c# .net php attilax总结
Atitit.http httpclient实践java c# .net php attilax总结 1. Navtree>> net .http1 2. Httpclient理论1 2. ...
- 使用httpclient发送get或post请求
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
随机推荐
- Win32 Windows规划 三
一.NMAKE 和 Makefile 1.1 NMAKE - 命令解释器. 依据Makefile文件里定义的脚本.完毕项目的编译等操作 1.2 Makefile - 定义编译.连接等脚本语言 1.3 ...
- Ewebeditor最新漏洞和漏洞指数
Ewebeditor最新漏洞和漏洞指数[收集] 来源:转载作者:佚名时间:2009-06-03 00:04:26 下面文章收集转载于网络:) 算是比較全面的ewebeditor编辑器的漏洞收集,如今的 ...
- Error 56: The Cisco Systems, Inc. VPN Service has not been started(Cisco VPN在Vista下出现Error 56的解决办法)
Error 56: The Cisco Systems, Inc. VPN Service has not been started(Cisco VPN在Vista下出现Error 56的解决办法) ...
- rsync+inotify实现server实时备份
inotify实现对文件夹下文件进行监听的原理: inotify集成到内核中,通过内核提供的接口.使用inotify作为第三方的软件对文件夹变化进行监控. inotifywait命令能够对文件夹中的文 ...
- Bug记录:微博的Java SDK返回经纬度错误
现象:美国的坐标点可能会定位到西藏地区-后发现原来负经度经解析后,均变成正的! 源码: private void getGeoInfo(String geo) { StringBuffer value ...
- Javascript作用域问题的构造函数的变量
构造函数new对于使用.代表创建对象.此外,它可以被用作普通的函数调用,因为它也是一个功能. function Person(name) { this.name=name; } Person(12); ...
- WWDC2014开源
A Cocoa OSX App to help you download WWDC2014 videos 地址:https://github.com/iosxtools/WWDC2014 版权声明:本 ...
- 交互式命令 expect
shell尽管很强大.但是貌似无法完成交互式命令的操作,实例 ssh host 如果host而且该机没有加入信任.手动输入的时间需要password. 这样的情况下可以使用expect支持. 下面举个 ...
- Sonar——代码质量管理平台
Sonar——代码质量管理平台 一.基本认识 Sonar (SonarQube)是一个开源平台,用于管理源代码的质量. Sonar 不只是一个质量数据报告工具,更是代码质量管理平台.通过插件机制,So ...
- 如何实现Web聊天
假设你web聊天不知道这件事情,那么最好的方法可能是:openfire+jsjac openfire它是java做开源xmppserver,jsjac它是javascript做开源的Web版本xmpp ...