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)是目前互联网上极其普遍的传输协议,它为构建功 ...
随机推荐
- hdu 1875 畅通工程再续(prim方法求得最小生成树)
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1875 /************************************************* ...
- 菜鸟学SSH(九)——Hibernate——Session之save()方法
Session的save()方法用来将一个临时对象转变为持久化对象,也就是将一个新的实体保存到数据库中.通过save()将持久化对象保存到数据库需要经过以下步骤: 1,系统根据指定的ID生成策略,为临 ...
- Why-are-GPUs-well-suited-to-deep-learning
https://www.quora.com/Why-are-GPUs-well-suited-to-deep-learning http://timdettmers.com/2015/03/09/de ...
- Vue.js使用-组件示例(实现数据的CRUD)
1.业务场景 用户(姓名,年龄,性别)的增删改查 2.数据格式 定义字段,name:字段名称,iskey:是否主键(添加,修改数据标志),dataSource:可选列表(下拉框选项) columns: ...
- java只使用try和finally不使用catch的原因和场景
JDK并发工具包中,很多异常处理都使用了如下的结构,如AbstractExecutorService,即只有try和finally没有catch. class X { private final Re ...
- mysql load本地文件失败,提示access denied
mysql load本地文件失败,提示access denied 解决方式 直接谷歌到stackoverflow,解决方式如下 mysql -u myuser -p --local-infile so ...
- linux centOS6 nexus 开启自动启动
sudo ln -s /opt/nexus-2.6.4/nexus-2.6.4-02/bin/nexus /etc/init.d/nexus 使用 service nexus status/star ...
- Zabbix监控JVM内存
上篇最后提到了jstat,jstat可以查看统计JVM内存信息,那么结合Zabbix,就可以监控多实例的JVM内存了. 1.下面两个脚本部署在被监控主机: vm.py 用于JVM实例PID查找,ps命 ...
- Upload文件时出现"Cannot access a closed file"错误
本地能上传文件,部署到服务器上就报 Cannot access a closed file 错误,以下是解决方法: <System.Web> <httpRuntime executi ...
- iosg给父类view添加透明度子类也变得透明
用如下方式给父类view设置透明度不要使用alpha设置 self.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponen ...