基于版本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简介的更多相关文章

  1. Taro Next H5 跨框架组件库实践

    作者:凹凸曼 - JJ Taro 是一款多端开发框架.开发者只需编写一份代码,即可生成各小程序端.H5 以及 React Native 的应用. Taro Next 近期已发布 beta 版本,全面完 ...

  2. REST简介

    一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...

  3. react学习与简介

    简介: React是Facebook开发的一款JS库 React解决了什么问题? 1).首先是以往mvc模式的缺陷,当代码库庞大时,mvc非常的复杂,每添加新的功能,项目的复杂度就几何倍的增长,导致代 ...

  4. 解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介

    ASP.NET 5简介 ASP.NET 5是一个跨时代的改写,所有的功能和模块都进行了独立拆分,做到了彻底解耦.为了这些改写,微软也是蛮 拼的,几乎把.NET Framwrok全部改写了一遍,形成了一 ...

  5. 主成分分析(principal components analysis, PCA)

    原理 计算方法 主要性质 有关统计量 主成分个数的选取 ------------------------------------------------------------------------ ...

  6. R语言数据处理利器——dplyr简介

    dplyr是由Hadley Wickham主持开发和维护的一个主要针对数据框快速计算.整合的函数包,同时提供一些常用函数的高速写法以及几个开源数据库的连接.此包是plyr包的深化功能包,其名字中的字母 ...

  7. SpringBoot常用配置简介

    SpringBoot常用配置简介 1. SpringBoot中几个常用的配置的简单介绍 一个简单的Spring.factories # Bootstrap components org.springf ...

  8. [转]REST简介

    转自:http://www.cnblogs.com/loveis715/p/4669091.html 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的 ...

  9. UML精粹1 - 简介

    Martin的主页 http://martinfowler.com/. Pavel Hruby开发的visio模板,可以用来画UML图: http://phruby.com 简介 统一建模语言UML是 ...

随机推荐

  1. [Android]Android内存泄漏你所要知道的一切(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/7235616.html Android内存泄漏你所要知道的一切 ...

  2. 使用JavaScript开发跨平台的桌面应用

    任何可以使用JavaScript来编写的应用,最终会由JavaScript编写.--Atwood定律 Atwood's Law是Jeff Atwood在2007年提出的:"any appli ...

  3. linux服务器部署jar包以及shell脚本的书写

    背景:记录在linux环境下部署jar程序的过程 1 部署过程记录 1.1 程序结构 这里的main函数就在DemRest2.java 文件中. 为了部署方便,要做到以下两点: 1 在导出的jar包中 ...

  4. H5微信通过百度地图API实现导航方式一

    根据业务需求修改百度API,实现微信中的导航功能.因为源码中SearchInfoWindow_min.js有点小问题(部分小城市公交线路少,查不到路线时没有提示),所以这里在源码的基础上改了一点点.可 ...

  5. MongoDB备份和恢复

    mongodump备份数据 该命令可以导出所有数据到指定目录中, 也能通过参数指定备份服务器 mongodump -h dbhost -d dbname -o dbdirectory dbhost: ...

  6. 50. leetcode 520. Detect Capital

    520. Detect Capital Given a word, you need to judge whether the usage of capitals in it is right or ...

  7. expdp导出文件,ORA-01555: 快照过旧: 回退段号 716

    快照号过旧,回退段号过小,信息如下:ORA-31693: 表数据对象 "CZBSDB"."SMS_RESULT_RECORD" 无法加载/卸载并且被跳过, 错误 ...

  8. Head First 设计模式 第6章 命令模式

    第6章 命令模式 在本章,我们将把封装带到一个全新的境界,把方法调用封装起来.没错,通过方法调用,我们可以把运算块包装成型.所以,调用此运算的对象不需要关心运算是如何进行的,只要知道如何使用包装成型的 ...

  9. Loadrunner分布式测试

    据经验,每生成一个虚拟用户,需要花费负载生成器大约 2M-3M 的内存空间.通常运行 controller的主机很少用作负载生成器.负载生成器的工作多由其他装有 LR Agent的PC 机来担任.如果 ...

  10. 社群系统ThinkSNS V4.5.29 APP更新发布,新增用户认证及系统消息

    社群系统ThinkSNS V4版本移动端APP将于7月29日更新发布,本次更新修复部分bug,最主要是增加了移动端APP的用户认证功能,以及添加了系统消息,为V4.5.29版本发布.这两个功能PC端的 ...