1、为什么要使用HttpClient
想必大家对对网络协议的http协议,并不陌生。因为越来越多的Java程序需要通过http协议来进行访问,在jdk中有HttpURLConnection相关使用,提供了关于Http但是对于开发来说提供的功能还不够灵活。但是Apache的HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,可以提高开发的效率,也方便提高代码的健壮性。因此掌握HttpClient是相当重要的。
2、HttpClient的特性
(1)基于标准,纯Java,实现HTTP 1.0和1.1版本
(2)在可扩展OO框架中完全实现所有HTTP方法(GET,POST,PUT,DELETE,HEAD,OPTIONS和TRACE)。
(3)支持使用HTTPS(HTTP over SSL)协议加密。
(4)通过HTTP代理的透明连接。
(5)通过CONNECT方法通过HTTP代理隧穿HTTPS连接。
(6)Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方
(7)插件式的自定义认证方案。
(8)便携可靠的套接字工厂使它更容易的使用第三方解决方案。
(9)连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
(10)自动处理Set-Cookie中的Cookie。
(11)插件式的自定义Cookie策略。
(12)Request的输出流可以避免流中内容直接缓冲到socket服务器。
(13)Response的输入流可以有效的从socket服务器直接读取相应内容。
(14)在http1.0和http1.1中利用KeepAlive保持持久连接。
(15)直接获取服务器发送的response code和 headers。
(16)设置连接超时的能力。
(17)实验性的支持http1.1 response caching。
(18)源代码基于Apache License 可免费获取。
3、依赖的jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
4、get请求带参数与不带参数
/** * get请求 * @throws URISyntaxException */ @Test public void doGetTest() throws IOException, URISyntaxException { // 获取httpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 如果没有参数则可以直接 HttpGet q = new HttpGet("http://www.baidu.com"); // 如果有参数,需要按如下方法来设置参数 URI uri = new URIBuilder("http://www.baidu.com/s").addParameter("kw", "java").build(); HttpGet q = new HttpGet(uri); CloseableHttpResponse response = null; try { // 执行请求 response = httpClient.execute(q); int code = response.getStatusLine().getStatusCode(); if (code == 200) { //获取响应内容 String content = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(content); } response.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != response) { response.close(); } httpClient.close(); } }
5、post请求带参数与不带参数
/**
* post请求
* @throws URISyntaxException
*/
@Test
public void doPostTest() throws IOException, URISyntaxException {
// 获取httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 如果没有参数则可以直接 HttpPost q = new HttpPost("http://www.baidu.com");
// 如果有参数,需要按如下方法来设置参数
HttpPost p = new HttpPost("http://www.oschina.net/search");
List<NameValuePair> param = new ArrayList<NameValuePair>();
//https://www.oschina.net/search?scope=project&q=java
param.add(new BasicNameValuePair("scope", "project"));
param.add(new BasicNameValuePair("q", "java"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(param, "utf-8");
p.setEntity(entity);
p.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(p);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//获取响应内容
String content = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(content);
}
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != response) {
response.close();
}
httpClient.close();
}
}