HTTP Components简介
基于版本4.5.x
简介
组件
- HttpClient,核心组件
- HC Fluent,提供了流式操作接口
- HttpMime,提供文件上传时用到的一些工具类
- HttpClient Cache,有待学习
- HttpClient OSGi,有待学习
特性
- 基于标准、纯净的Java语言。实现了Http1.0和Http1.1
- 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
- 支持HTTPS(基于SSL的HTTP)协议。
- 通过HTTP代理建立透明的连接。
- 利用CONNECT方法通过HTTP代理建立隧道的HTTPS连接。
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO, Kerberos认证方案。
- 插件式的自定义认证方案。
- 便携可靠的套接字工厂使它更容易的使用第三方解决方案(Pluggable secure socket factories, making it easier to use third party solutions)。
- 支持多线程应用的连接管理器。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
- 自动处理Set-Cookie中的Cookie。(Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.)
- 插件式的自定义Cookie策略。
- Request的输出流可以避免流中内容直接缓冲到socket服务器。(Request output streams to avoid buffering any content body by streaming directly to the socket to the server.)
- Response的输入流可以有效的从socket服务器直接读取相应内容。
- 在http1.0和http1.1中利用KeepAlive保持持久连接。
- 直接获取服务器发送的response code和 headers。
- 可设置连接超时。
- 支持http1.1 response caching。
- 源代码基于Apache License 可免费获取。
Quick Start
HTTP Client
GET请求、POST请求 及 response处理
CloseableHttpClient httpclient = HttpClients.createDefault();
//GET请求及response处理
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
//POST请求及response处理
HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
官网的例子注释中有几点是需要注意的:
- 调用httpclient.execute(XXX)后,http连接会一直被response持有,需要调用CloseableHttpResponse#close(),当然也可是已使用jdk1.7的try-catch-resource。
- 如果response没有充分的被消耗掉(比如:chunk模式下,只取了部分),会被connection manager丢弃而不能复用,使用
EntityUtils.consume(entity)可以确保response被充分消耗
HC Fluent 的流式接口
Request.Get("http://targethost/homepage")
.execute().returnContent();
Request.Post("http://targethost/login")
.bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
.execute().returnContent();
HttpMime 提交文件
multipart/form 类型的POST,下面例子中的FileBody、StringBody、MultipartEntityBuilder等都是HttpMine模块中的类。
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/fileUpload");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
参考
HTTP Client使用详解
HttpClient Quick start
HTTP Components简介的更多相关文章
- Taro Next H5 跨框架组件库实践
作者:凹凸曼 - JJ Taro 是一款多端开发框架.开发者只需编写一份代码,即可生成各小程序端.H5 以及 React Native 的应用. Taro Next 近期已发布 beta 版本,全面完 ...
- REST简介
一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...
- react学习与简介
简介: React是Facebook开发的一款JS库 React解决了什么问题? 1).首先是以往mvc模式的缺陷,当代码库庞大时,mvc非常的复杂,每添加新的功能,项目的复杂度就几何倍的增长,导致代 ...
- 解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介
ASP.NET 5简介 ASP.NET 5是一个跨时代的改写,所有的功能和模块都进行了独立拆分,做到了彻底解耦.为了这些改写,微软也是蛮 拼的,几乎把.NET Framwrok全部改写了一遍,形成了一 ...
- 主成分分析(principal components analysis, PCA)
原理 计算方法 主要性质 有关统计量 主成分个数的选取 ------------------------------------------------------------------------ ...
- R语言数据处理利器——dplyr简介
dplyr是由Hadley Wickham主持开发和维护的一个主要针对数据框快速计算.整合的函数包,同时提供一些常用函数的高速写法以及几个开源数据库的连接.此包是plyr包的深化功能包,其名字中的字母 ...
- SpringBoot常用配置简介
SpringBoot常用配置简介 1. SpringBoot中几个常用的配置的简单介绍 一个简单的Spring.factories # Bootstrap components org.springf ...
- [转]REST简介
转自:http://www.cnblogs.com/loveis715/p/4669091.html 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的 ...
- UML精粹1 - 简介
Martin的主页 http://martinfowler.com/. Pavel Hruby开发的visio模板,可以用来画UML图: http://phruby.com 简介 统一建模语言UML是 ...
随机推荐
- Android 自定义帧动画
Android 自定义帧动画 Android L : Android Studio 帧动画 和gif图片类似,顺序播放准本好的图片文件:图片资源在xml文件中配置好 将图片按照预定的顺序一张张切换,即 ...
- hdu_5810:Balls and Boxes(期望)
这题似乎就是纯概率论.. E(V)=D(X_i)=npq (p=1/m,p+q=1) #include<bits/stdc++.h> using namespace std; typede ...
- 【SignalR学习系列】1. SignalR理论介绍
什么是SignalR? ASP.NET SignalR 是一个让 ASP.NET开发者可以简单地给自己的程序添加即时通讯功能的开发库.即时通讯功能可以直接从服务器端给在线的客户端发送数据,而不用等待客 ...
- vim 配置插件
vim插件可以用bundle管理,我这里面用的是一个开源的Vundle工具,git上操作步骤说的很清楚https://github.com/VundleVim/Vundle.vim 之前PluginI ...
- 简单设置android启动画面
1.新建Activity,以及layout文件夹里的xml文件2.将新建Activity在AndroidManifest中设为默认Activity,并且添加:android:theme="@ ...
- java web 中有效解决中文乱码问题-pageEncoding与charset区别, response和request的setCharacterEncoding 区别
这里先写几个大家容易搞混的编码设置代码: 在jsp代码中的头部往往有这两行代码 pageEncoding是jsp文件本身的编码contentType的charset是指服务器发送给客户端时的内容编码J ...
- 关于Visual Studio调试 无效指针提示
前几天遇到了这个问题,编译没问题,直接运行没问题 但是一调试,会提示无效指针,(按Ctrl+F5可以运行,但按F5提示无效指针) 只要这样,新建C:\ProgramData\Microsoft Vis ...
- Java基础之TCP与UDP
OSI 7层参考模型 物理层 --> 数据链路层 --> 网络层 --> 传输层 --> 会话层 --> 表示层 --> 应用层 按此顺序称为拆包,反之为封包. T ...
- easyui项目问题集锦
1.级联问题(combobox) combobox至多可以保存2个东西value和text,但我需要第三个数的时候,怎么办?比如,省.市.区的三级级联,我选择市的时候,需要市id,市name,区号,邮 ...
- Python [目录]
[第一篇] Python 发展历史 [第二篇] Python 优缺点 [第三篇] Python 应用场景 [第四篇] Python Hello World程序 [第五篇] Python 基础知识 [第 ...