基于版本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. Java IO 之 BIO、NIO、AIO

    1.BIO.NIO.AIO解释 Java BIO : 同步并阻塞 (Blocking IO) 一个连接一个线程 即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不 ...

  2. Objective-C 自定义UISlider滑杆 分段样式

    效果 自定义一个功能简单的分段的滑杆 可显示分段名 为了显示效果,我们将滑块和节点都设置为不规则 这里只实现了分段的slider,未分段的没有实现,有兴趣的可以定义另一种类型做个判断修改下 需求分析 ...

  3. 【jquery】获取元素高度

    1. $("#div_id").height(); // 获得的是该div本身的高度, (不包含padding,margin,border)2. $("#div_id&q ...

  4. 简单聊聊不可或缺的Nginx反向代理服务器--实现负载均衡【上篇】

    今天又是新的一周,我养足了精神去对待新一周的工作,但是今天到公司发现还是有一点空闲时间的,所以就想与之前接触过的Nginx再交往得更深一点儿. 什么是Nginx: Nginx是一款高性能的http服务 ...

  5. 踩坑之路_"var name = ' ';"_迷之BUG

    情景介绍:最近写一个拖拽生成图表的工具,自己的思路每次mousedown的时候动态将this的name属性值赋值给全局中变量(自己手贱测试时直接将变量名命名为了'name',一大波bug还有30s到达 ...

  6. HTML5基本知识点

    一.什么是HTML HTML是超文本标签语言,即网页的源码.而浏览器就是翻译解释HTML源码的工具. 二.HTML的基本格式 <!DOCTYPE html>: ①文档类型声明:让浏览器按照 ...

  7. Cocoapods 应用第一部分 - Xcode 创建 .framework 相关

    问题的提出: 随着项目的越来越大,可能会出现好几个团队共同维护一个项目的情况,例如:项目组A负责其中的A块,项目组B负责其中的B块.....这几块彼此之间既独立,也相互联系.对于这种情况,可以采用约定 ...

  8. 4.写一个控制台应用程序,接收一个长度大于3的字符串,完成下列功能: 1)输出字符串的长度。 2)输出字符串中第一个出现字母a的位置。 3)在字符串的第3个字符后面插入子串“hello”,输出新字符串。 4)将字符串“hello”替换为“me”,输出新字符串。 5)以字符“m”为分隔符,将字符串分离,并输出分离后的字符串。 */

    namespace test4 {/* 4.写一个控制台应用程序,接收一个长度大于3的字符串,完成下列功能: 1)输出字符串的长度. 2)输出字符串中第一个出现字母a的位置. 3)在字符串的第3个字符 ...

  9. .net 设置webbrowser控件使用的IE版本

    当我们在使用.net的Webbrowser控件时,发现webbrowser展示的内容和我们用浏览器展示的内容不一致,甚至出现:'JSON' is undefined. 原因是webbrowser使用的 ...

  10. 程序设计入门——C语言 习题汇总

    <img width="108" height="40" alt="浙江大学" src="http://imgsize.ph ...