HttpClient基础(一)

HttpClientApache Jakarta Common下的子项目,可以用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,本文采用的HttpClient版本是4.4.1
许多需要后台模拟请求的系统或者框架都用的是httpclient。所以作为一个java开发人员,有必要学一学。本文提供了一个简单的demo,供初学者参考。

  • 使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
    • 创建CloseableHttpClient对象。
    • 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
    • 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
    • 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
    • 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
    • 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;
    • 调用CloseableHttpResponse 的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
    • 释放连接。无论执行方法是否成功,都必须释放连接

下面是一个POST带参数请求的例子,访问天气网站,用到的HttpClient版本是4.4.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
public static String send(String url, Map<String, String> map, String encoding) throws IOException{
String body = "";

//1.创建对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.创建请求方式
HttpPost post = new HttpPost(url);
//3.装填参数
List<NameValuePair> nvp = new ArrayList<>();
if(map !=null){
for (Entry<String, String> entry : map.entrySet()) {
nvp.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//4.设置参数到请求对象中
post.setEntity(new UrlEncodedFormEntity(nvp,encoding));

System.out.println("请求地址:----"+url);
System.out.println("请求参数:-----"+nvp.toString());
//5.设置头部信息
post.setHeader("Content-type", "application/x-www-form-urlencoded");
post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

//6.执行请求
CloseableHttpResponse response = httpClient.execute(post);
//7.获取结果
HttpEntity entity = response.getEntity();

if(entity!=null){
//按指定编码转换结果实体为String类型
System.out.println("entity----"+entity);
body = EntityUtils.toString(entity, encoding);
}

response.close();
return body;
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) throws IOException {

String url="http://php.weather.sina.com.cn/iframe/index/w_cl.php";

Map<String, String> map = new HashMap<String, String>();
map.put("code", "js");
map.put("day", "0");
map.put("city", "武汉");
map.put("dfc", "1");
map.put("charset", "utf-8");
String body = send(url1, map,"utf-8");
System.out.println("交易响应结果:");
System.out.println(body);

System.out.println("-----------------------------------");

map.put("city", "北京");
body = send(url, map, "utf-8");
System.out.println("交易响应结果:");
System.out.println(body);

}

结果

1
2
3
4
5
6

请求地址:----http://php.weather.sina.com.cn/iframe/index/w_cl.php
请求参数:-----[dfc=1, charset=utf-8, code=js, city=武汉, day=0]
entity----org.apache.http.client.entity.DecompressingEntity@548e7350
交易响应结果:
(function(){var w=[];w['武汉']=[{s1:'晴',s2:'晴',f1:'qing',f2:'qing',t1:'28',t2:'20',p1:'≤3',p2:'≤3',d1:'无持续风向',d2:'无持续风向'}];var add={now:'2017-09-11 20:14:23',time:'1505132063',update:'北京时间09月11日17:10更新',error:'0',total:'1'};window.SWther={w:w,add:add};})();//0

注意,静态文件不接受post请求

ApacheIISNginx等绝大多数web服务器,都不允许静态文件响应POST请求,否则会返回HTTP/1.1 405 Method not allowed错误。

解决方法,修改nginx配置
1
2
3
4
5
location ^~ /m/coupon {
root /data/server/h5.weidian.com;
error_page 405 =200 https://$host$request_uri;

}

附各种请求的写法

1.GET请求
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
public class DoGET {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("内容长度:" + content.length());

}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

}

}
2.带参数的GET请求
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
public class DoGETParam {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 定义请求的参数
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();

System.out.println(uri);

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

}

}
3.POST请求
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
public class DoPOST {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/");

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

}

}
4.带参数的POST请求
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
public class DoPOSTParam {

public static void main(String[] args) throws Exception {

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/search");

// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

}

}
文章目录
  1. 1. 测试
  2. 2. 结果
  3. 3. 注意,静态文件不接受post请求
    1. 3.1. 解决方法,修改nginx配置
  4. 4. 附各种请求的写法
    1. 4.1. 1.GET请求
    2. 4.2. 2.带参数的GET请求
    3. 4.3. 3.POST请求
    4. 4.4. 4.带参数的POST请求
|