HttpComponents-Client学习
点击进入 我的为知笔记链接(带格式)
前言
1 HttpClient 范围
- 基于HttpCore的客户端侧HTTP传输库
- 基于阻塞式I/O
- 内容不可知
2 HttpClient不是什么
第一章 基础
1.1 request execution 请求的执行
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
<...>
} finally {
response.close();
}
1.1.1 HTTP request
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
1.1.2 HTTP response
HttpResponse response = new asicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
1.1.3 处理message headers
1.1.4 HTTP entity
1.1.5 确保释放low level resources
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
}
} finally {
response.close();
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int byteOne = instream.read();
int byteTwo = instream.read();
// Do not need the rest 不需要剩下的部分
}
} finally {
response.close();
}
1.1.6 消费entity content
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 2048) {
System.out.println(EntityUtils.toString(entity));
} else {
// Stream content out
}
}
} finally {
response.close();
}
CloseableHttpResponse response = <...>
HttpEntity entity = response.getEntity();
if (entity != null) {
entity = new BufferedHttpEntity(entity);
}
1.1.7 生成entity content
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file,
ContentType.create("text/plain", "UTF-8"));
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
1.1.7.1 HTML forms 表单 <TODO>
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);
1.1.7.2 Content chunking
StringEntity entity = new StringEntity("important message",
ContentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true);
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);
1.1.8 Response handlers 响应处理器 <TODO>
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/json");
ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {
@Override
public JsonObject handleResponse(final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
Gson gson = new GsonBuilder().create();
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
Reader reader = new InputStreamReader(entity.getContent(), charset);
return gson.fromJson(reader, MyJsonObject.class);
}
};
MyJsonObject myjson = client.execute(httpget, rh);
1.2 HttpClient 接口
ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
// Keep connections alive 5 seconds if a keep-alive value
// has not be explicitly set by the server
keepAlive = 5000;
}
return keepAlive;
}
};
CloseableHttpClient httpclient = HttpClients.custom().setKeepAliveStrategy(keepAliveStrat).build();
1.2.1 HttpClient 线程安全性 <TODO>
1.2.2 HttpClient 资源的释放
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
<...>
} finally {
httpclient.close();
}
1.3 HTTP execution context
- HttpConnection实例,代表到目标服务器的实际连接。
- HttpHost实例,代表连接目标。
- HttpRoute实例,代表完整的连接route。<TODO>
- HttpRequest实例,代表实际的HTTP request。在execution context中最终的HttpRequest对象,总是代表了发送到目标服务器的message state。默认情况下,HTTP/1.0 和 HTTP/1.1 使用相对的request URI。然而,如果request是通过proxy发送,在non-tuneling模式下,那URI就是绝对的。
- HttpResponse实例,代表了实际的HTTP response。
- Boolean对象,一个flag,用于指示实际请求是否被完全地发送到了连接目标。
- RequestConfig对象,代表了实际的请求配置。
- List<URI>对象,代表了在request execution过程中接收到的所有重定向地址的集合。
HttpContext context = <...>
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpHost target = clientContext.getTargetHost();
HttpRequest request = clientContext.getRequest();
HttpResponse response = clientContext.getResponse();
RequestConfig config = clientContext.getRequestConfig();
CloseableHttpClient httpclient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();
HttpGet httpget1 = new HttpGet("http://localhost/1");
httpget1.setConfig(requestConfig);
CloseableHttpResponse response1 = httpclient.execute(httpget1, context);
try {
HttpEntity entity1 = response1.getEntity();
} finally {
response1.close();
}
HttpGet httpget2 = new HttpGet("http://localhost/2");
CloseableHttpResponse response2 = httpclient.execute(httpget2, context);
try {
HttpEntity entity2 = response2.getEntity();
} finally {
response2.close();
}
1.4 HTTP 协议拦截器
CloseableHttpClient httpclient = HttpClients.custom().addInterceptorLast(new HttpRequestInterceptor() { // 添加拦截器
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AtomicInteger count = (AtomicInteger) context.getAttribute("count");
request.addHeader("Count", Integer.toString(count.getAndIncrement()));
}
}).build();
AtomicInteger count = new AtomicInteger(1);
HttpClientContext localContext = HttpClientContext.create();
localContext.setAttribute("count", count); // 初始化数据
HttpGet httpget = new HttpGet("http://localhost/");
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
HttpEntity entity = response.getEntity();
} finally {
response.close();
}
}
// 缺省了一步 localContext.getAttribute("count")
1.5 异常处理
1.5.1 HTTP传输安全性
1.5.2 幂等methods
1.5.3 自动的异常恢复
- HttpClient不会试图恢复任何逻辑的或者HTTP协议错误(派生自HttpException)。
- HttpClient会自动地重试那些幂等的方法。
- HttpClient会自动的重试那些 HTTP request仍被发送中的传输异常(例如 request没有完全发送)。
1.5.4 request retry handler 请求重试处理器
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();
1.6 放弃request <TODO>
1.7 重定向处理
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
CloseableHttpClient httpclient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://localhost:8080/");
CloseableHttpResponse response = httpclient.execute(httpget, context);
try {
HttpHost target = context.getTargetHost();
List<URI> redirectLocations = context.getRedirectLocations(); // 为嘛??
URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
System.out.println("Final HTTP location: " + location.toASCIIString());
// Expected to be an absolute URI
} finally {
response.close();
}
第二章 连接管理
2.1 连接持久化
2.2 HTTP connection routing 连接路由?
Plain routes are established by connecting to the target or the first and only proxy. Tunnelled routes are established by connecting to the first and tunnelling through a chain of proxies to the target. Routes without a proxy cannot be tunnelled. Layered routes are established by layering a protocol over an existing connection. Protocols can only be layered over a tunnel to the target, or over a direct connection without proxies.
2.2.1 route computation 路由计算
2.2.2 secure HTTP connection
2.3 HTTP connection managers 连接管理者 <TODO>
2.3.1 被管理的连接 和 连接管理者
HttpComponents-Client学习的更多相关文章
- Apache HttpComponents Client 4.0快速入门/升级-2.POST方法访问网页
Apache HttpComponents Client 4.0已经发布多时,httpclient项目从commons子项目挪到了HttpComponents子项目下,httpclient3.1和 h ...
- JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例
一.简述需求 平时我们需要在JAVA中进行GET.POST.PUT.DELETE等请求时,使用第三方jar包会比较简单.常用的工具包有: 1.https://github.com/kevinsawic ...
- 编程之路-client学习知识点纲要(Web/iOS/Android/WP)
Advanced:高级内容 Architect:架构设计 Core:框架底层原理分析 Language:框架经常使用语言 Objective-C Dart Swift Java Network:网络 ...
- Apache HttpComponents 学习
基本上,用户常用的就是HttpClient:它基于Http Core部分,但 Core部分太过于 low level,不建议使用,除非有特殊需要. Apache HttpComponentsTM 项目 ...
- HttpClient 入门教程学习
HttpClient简介 HttpClient是基于HttpCore的HTTP/1.1兼容的HTTP代理实现. 它还为客户端认证,HTTP状态管理和HTTP连接管理提供可重用组件. HttpCompo ...
- java使用httpcomponents 上传文件
一.httpcomponents简介 httpcomponents 是apache下的用来负责创建和维护一个工具集的低水平Java组件集中在HTTP和相关协议的工程.我们可以用它在代码中直接发送htt ...
- apache开源项目--HttpComponents
HttpComponents 也就是以前的httpclient项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端/服务器编程工具包,并且它支持 HTTP 协议最新的版本和建议.不 ...
- HttpComponents 也就是以前的httpclient项目
HttpComponents 也就是以前的httpclient项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端/服务器编程工具包,并且它支持 HTTP 协议最新的版本和建议.不 ...
- HttpComponents入门解析
1 简介 超文本传输协议(http)是目前互联网上极其普遍的传输协议,它为构建功能丰富,绚丽多彩的网页提供了强大的支持.构建一个网站,通常无需直接操作http协议,目前流行的WEB框架已经透明的将这些 ...
- HttpComponents了解
原文地址:http://blog.csdn.net/jdluojing/article/details/7300428 1 简介 超文本传输协议(http)是目前互联网上极其普遍的传输协议,它为构建功 ...
随机推荐
- mongodb学习比较(数据操作篇)
1. 批量插入: 以数组的方式一次插入多个文档可以在单次TCP请求中完成,避免了多次请求中的额外开销.就数据传输量而言,批量插入的数据中仅包含一份消息头,而多次单条插入则会在每次插入数据时封 ...
- npm WARN build `npm build` called with no arguments. Did you mean to `npm run-script build`?
跑npm build结果如下: npm WARN build `npm build` called with no arguments. Did you mean to `npm run-script ...
- Java map双括号初始化方式的问题
关于Java双括号的初始化凡是确实很方便,特别是在常量文件中,无可替代.如下所示: Map map = new HashMap() { { put("Name", "Un ...
- Standard C 之 math.h和float.h
对于C Standard Library 可以参考:http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ 或者 http://www.cplusplus.c ...
- linux命令(49):显示文件的指定行,打印中间几行
linux 如何显示一个文件的某几行(中间几行) [一]从第3000行开始,显示1000行.即显示3000~3999行 cat filename | tail -n +3000 | head -n 1 ...
- 【数据库】悲观锁与乐观锁与MySQL的MVCC实现简述
悲观锁 悲观锁,就是一种悲观心态的锁,每次访问数据时都会锁定数据: 乐观锁 乐观锁,就是一种乐观心态的锁,每次访问数据时并不锁定数据,期待数据并没作修改,如果数据没被修改则作具体的业务 应用程序上使用 ...
- VirtualBox与VMWare网络冲突
VirtualBox安装一个XP后,发现老是上不到网,怎么折腾都不行, 后来发现设备管理器中 vmware accelerated amd pcnet adapter #2显示黄色感叹号 不对呀,这是 ...
- Zookeeper之Zookeeper的Client的分析
1)几个重要概念 ZooKeeper:客户端入口 Watcher:客户端注册的callback ZooKeeper.SendThread: IO线程 ZooKeeper.EventThread: 事件 ...
- eclipse Maven 使用记录 ------ 建立app项目
maven 项目构建工具 , 如今已逐渐取代ant的笨拙配置方式 ,使项目管理更加简单,规范,结构更加清晰,这里记录跟eclipse集成的一些步骤 1.从apache maven项目下下载maven ...
- mysql 系统表的作用
mysql 的系统表记录了所有数据库表(包括视图的定义语句)的字段列,顺序,类型等等,知道这些的话可以做些抽取模板淫荡的操作吧 嘿嘿 public void shuaxinglb() { try { ...