HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
<!-- HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
public class HttpGetTest {
public static void main(String[] args) {
// 创建 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpGet 对象,需要设置 url 访问地址
//String url = "http://www.itcast.cn";
String url = "https://www.baidu.cn";
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
// 使用 HttpClient 发起请求,获取 response 响应
response = httpClient.execute(httpGet);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
//System.out.println(content);
System.out.println(content.length());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭 response
response.close();
// 关闭 httpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class HttpGetParamTest {
public static void main(String[] args) throws URISyntaxException {
// 创建 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 设置请求地址:http://yun.itheima.com/tiyan/java?bz=spk
String url = "http://yun.itheima.com/tiyan/java";
// 创建URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 设置参数
uriBuilder.setParameter("bz", "spk");
//uriBuilder.setParameter("bz", "spk").setParameter("", "");
// 创建 HttpGet 对象,需要设置 url 访问地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
//发起请求的信息: GET http://www.itcast.cn HTTP/1.1
System.out.println("发起请求的信息: " + httpGet);
CloseableHttpResponse response = null;
try {
// 使用 HttpClient 发起请求,获取 response 响应
response = httpClient.execute(httpGet);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
//System.out.println(content);
System.out.println(content.length());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭 response
response.close();
// 关闭 httpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class HttpPostTest {
public static void main(String[] args) {
// 创建 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPost 对象,需要设置 url 访问地址
String url = "http://www.itcast.cn";
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
// 使用 HttpClient 发起请求,获取 response 响应
response = httpClient.execute(httpPost);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
//System.out.println(content);
System.out.println(content.length());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭 response
response.close();
// 关闭 httpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class HttpPostParamTest {
public static void main(String[] args) throws UnsupportedEncodingException {
// 创建 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPost 对象,需要设置 url 访问地址
String url = "http://yun.itheima.com/search";
HttpPost httpPost = new HttpPost(url);
// 声明 List 集合,封装表单中的请求参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("keys", "Java"));
// 创建表单的Entity对象,第一个参数是封装好的表单数据,第二个参数是编码
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf8");
// 设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// 使用 HttpClient 发起请求,获取 response 响应
response = httpClient.execute(httpPost);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
//System.out.println(content);
System.out.println(content.length());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭 response
response.close();
// 关闭 httpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。
测试以下代码,并断点查看每次获取的HttpClient都是不一样的。
public class HttpClientPoolTest {
public static void main(String[] args) {
// 创建连接池管理器
PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
// 设置最大连接数
manager.setMaxTotal(100);
// 设置每个主机的最大连接数,防止HOST不均衡
manager.setDefaultMaxPerRoute(10);
// 使用连接池管理器发起请求
doGet(manager);
doGet(manager);
}
private static void doGet(PoolingHttpClientConnectionManager manager) {
// 不是每次创建新的 HttpClient,而是从连接池中获取 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(manager).build();
// 创建 HttpGet 对象,需要设置 url 访问地址
String url = "http://www.itcast.cn";
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
// 不能关闭 HttpClient,由连接池管理了
//httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间
public class HttpConfigTest {
public static void main(String[] args) {
// 创建 HttpClient 对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpGet 对象,需要设置 url 访问地址
String url = "http://www.itcast.cn";
HttpGet httpGet = new HttpGet(url);
// 配置请求信息
RequestConfig config = RequestConfig.custom()
// 设置创建连接的最长时间,单位毫秒
.setConnectTimeout(1000)
// 设置获取连接的最长时间,单位毫秒
.setConnectionRequestTimeout(500)
// 设置数据传输的最长时间,单位毫秒
.setSocketTimeout(10 * 1000)
.build();
// 给请求设置请求信息
httpGet.setConfig(config);
CloseableHttpResponse response = null;
try {
// 使用 HttpClient 发起请求,获取 response 响应
response = httpClient.execute(httpGet);
// 解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
//System.out.println(content);
System.out.println(content.length());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭 response
response.close();
// 关闭 httpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}