超文本传输协议(http)是目前互联网上极其普遍的传输协议,它为构建功能丰富,绚丽多彩的网页提供了强大的支持。构建一个网站,通常无需直接操作 http 协议,目前流行的 WEB 框架已经透明的将这些底层功能封装的很好了。
除了作为网站系统的底层支撑,http 同样可以在其它的一些场景中使用,如游戏服务器和客户端的传输协议、web service、 网络爬虫、HTTP代理、网站后台数据接口等。
Http Components 对 HTTP 底层协议进行了很好的封装。
HttpComponents Core 简称 HttpCore, 是一组底层 Http 传输协议组件,支持两种 I/O 模型,阻塞 I/O 模型和和非阻塞 I/O 模型。上层组件(HttpComponents Client, HttpComponents AsyncClient)依赖此组件实现数据传输。
阻塞 I/O 模型基于基本的 JAVA I/O 实现,非阻塞模型基于 JAVA NIO 实现。
HttpComponents Client 建立在 HttpCore 之上的 Http 客户端管理组件。底层基于 HttpCore 阻塞I/O。从 Commons HttpClient 3.x 继承而来,Commons HttpClient 原来是 apache commons 组建的一部分,现在被 HttpComponents Client 所替代了。
原始的 Commons HttpClient 3.x 可以在 https://hc.apache.org/httpclient-legacy/index.html 找到。如下图:

HttpComponents AsyncClient 建立在 HttpCore NIO 模型之上的 Http 客户端,与基于阻塞 I/O 的 HttpComponents Client 形成互补,由于底层使用的 NIO 非阻塞模型,所以适用于高性能的应用场景。
首先打开 https://hc.apache.org/,点击左侧的 Download 链接,进入下载页面,下载最新版本的 HttpComponents。如下图:

在下载页面选择你需要下载的版本。将下载的压缩包进行解压,lib 目录下是 HttpComponents 和它依赖的类库,将它们放到你的工程 classpath 中,如果依赖文件已经存在了,不要放置多份,以免类库之间的冲突。如下图:

然后需要检查一下工程的 classpath 中是否存在 commons http 包。Commons http 与 HttpComponents 是完全两个东西,HttpComponents 中的 Client 是从 Commons http 继承而来的,所以很多类名是相同的。为了避免出现莫名奇妙的问题,应将 Commons http 从工程中删除(当然,如果你认为自己足够聪明,也可以在引用java包时小心区分)。
下面实例将通过 Get 方法请求 https://www.hxstrive.com 网址的内容,将内容输出到控制条。代码如下:
package com.huangx.httpcomponents;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 使用 HttpComponents 发起 GET 请求
* @author huangxin 2019/12/2
*/
public class GetDemo {
public static void main(String[] args) throws Exception {
// (1) 创建HttpGet实例
HttpGet get = new HttpGet("https://www.hxstrive.com");
// (2) 使用HttpClient发送get请求,获得返回结果HttpResponse
HttpClient http = new DefaultHttpClient();
HttpResponse response = http.execute(get);
// (3) 读取返回结果
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
}