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是 ...
随机推荐
- Jenkins: 执行 PowerShell 命令
Jenkins 默认是不支持执行 PowerShell 命令的,需要安装插件才能完成这样的任务.本文将介绍 Jenkins PoserShell 插件的基本用法和常见问题. 安装 PowerShell ...
- Spark笔记——技术点汇总
目录 概况 手工搭建集群 引言 安装Scala 配置文件 启动与测试 应用部署 部署架构 应用程序部署 核心原理 RDD概念 RDD核心组成 RDD依赖关系 DAG图 RDD故障恢复机制 Standa ...
- sqlserver的触发器练习实例
触发器的概念:它是由事件驱动的,就像java中的监听,当某个事件发生了,就会做一些工作. 下面直接上干货,创建insert触发器.delete触发器.DDL触发器和如何查看触发器定义 1.创建三个表学 ...
- 学会用requirejs,5分钟足矣
学会用requirejs,5分钟足矣 据说公司的项目较多的用到requirejs管理依赖,所以大熊同学挤出了5分钟休息时间学习了一下,现在分享一下.如果你想了解requirejs的实现原理,请绕道!如 ...
- MyBatis 框架的搭建和配置
MyBatis是支持定制化SQL.存储过程以及高级映射的优秀持久层框架.MyBatis 避免了几乎所有的JDBC代码和手动设置参数以及获取结果集.MyBatis可以对配置和原生Map使用简单的xml或 ...
- 设计模式--单例模式(Singleton pattern)及应用
单例模式 参考文档: 该文仅介绍spring的单例模式:spring 的单例模式 介绍原理:Spring的单例模式底层实现 参考书籍:漫谈设计模式:从面向对象开始-刘济华.pdf 1. 单例模式解析 ...
- BZOJ-1491-社交网络
题目链接:https://vjudge.net/problem/HYSBZ-1491 题目大意:中文题目,题意见题目 题目分析:由于数据量很小,可以考虑进行Floyd算法. 第一次进行Floyd算法, ...
- 利用GPU实现大规模动画角色的渲染
0x00 前言 我想很多开发游戏的小伙伴都希望自己的场景内能渲染越多物体越好,甚至是能同时渲染成千上万个有自己动作的游戏角色就更好了. 但不幸的是,渲染和管理大量的游戏对象是以牺牲CPU和GPU性能为 ...
- Flunetd 用于统一日志记录层的开源数据收集器
传统的日志查看方式 使用fluentd之后 一.介绍 Fluentd是一个开源的数据收集器,可以统一对数据收集和消费,以便更好地使用和理解数据. 几大特色: 使用JSON统一记录 简单灵活可插拔架构 ...
- 微信小程序开发-新闻列表之新闻列表绑定
微信小程序开发-新闻列表之新闻列表绑定开发教程: 1.效果图预览 2.准备工作 在拿到效果图后不要先急着去写代码,而是要去分析一下页面的整体结构,用什么方式定位和布局.小程序里建议使用flex布局,因 ...