0%

Java使用HttpClient库发送请求

HttpClient介绍

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载和安装

下载地址
http://hc.apache.org/downloads.cgi

下载二进制文件后解压lib文件夹,将jar包复制粘贴到项目目录,右击add to Build Path.
关联源码到httpcomponents-asyncclient-4.1.1-src\httpcomponents-asyncclient-4.1.1\目录即可查看源码。

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public static void post() {
// 创建HttpClient实例对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建Post请求
HttpPost httppost = new HttpPost(
"http://localhost:8080/服务端/servlet/Login");

// 创建参数列表
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams.add(new BasicNameValuePair("user", "lisi"));
formparams.add(new BasicNameValuePair("pwd", "123456"));

UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

// 设置廉洁配置
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());

// 执行连接操作
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {

// 遍历Header
Header[] allHeaders = response.getAllHeaders();
for (Header h : allHeaders) {
System.out
.println(h.getName() + " : " + h.getValue());
}

// 打印正文
System.out
.println("--------------------------------------");
System.out.println("Response content: "
+ EntityUtils.toString(entity, "UTF-8"));
System.out
.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}