HttpClient官网

本文参考地址:【CSDN】HttpClient详细使用示例 justry_deng

HttpClient主要用于访问其他接口

准备

引入相关依赖:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>

fastjson有将对象转化为json字符串的功能等。

这里使用的是4.5版本的httpclient,各个版本在使用上会有差异。


用于以下案例的测试:

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
@RestController
public class MyController {

@GetMapping("/doGet1")
public String doGet1() {
return "这个Get请求没有任何参数";
}

@GetMapping("/doGet2")
public String doGet2(String name, Integer age) {
return name + "今年" + age + "岁了";
}

@PostMapping("/doPost1")
public String doPost1() {
return "这个Post请求没有任何参数";
}

@PostMapping("/doPost2")
public String doPost2(String name, Integer age) {
return name + "今年" + age + "岁了";
}

@PostMapping("/doPost3")
public String doPost3(@RequestBody User user) {
return user.toString();
}

@PostMapping("/doPost4")
public String doPost4(@RequestBody User user, Integer flag, String meaning) {
return user.toString() + "\n" + flag + ">>>" + meaning;
}
}

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
35
36
public static void doGet1() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Get请求
HttpGet httpGet = new HttpGet("http://localhost:8080/doGet1");
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

有参方式一

  • 手动在url后面加上参数
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
61
62
public static void doGet2() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 参数
StringBuilder params = new StringBuilder();
try {
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name=")
.append(URLEncoder.encode("阿楠", "utf-8"))
.append("&")
.append("age=24");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

// 创建Get请求
HttpGet httpGet = new HttpGet("http://localhost:8080/doGet2" + "?" + params);
// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();

// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);

// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

有参方式二

  • 将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例
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
61
62
63
64
65
66
public static void doGet3() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 参数
URI uri = null;
try {
// 将参数放入键值对类NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", "阿楠"));
params.add(new BasicNameValuePair("age", "18"));
// 设置uri信息,并将参数集合放入uri;
// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("localhost")
.setPort(8080).setPath("/doGet2")
.setParameters(params).build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
// 创建Get请求
HttpGet httpGet = new HttpGet(uri);

// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();

// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);

// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

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
public static void doPost1() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/doPost1");
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

有参(普通参数)

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
public static void doPost2() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// 参数
StringBuilder params = new StringBuilder();
try {
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name=").append(URLEncoder.encode("nan", "utf-8"))
.append("&")
.append("age=24");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

// 创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/doPost2" + "?" + params);

// 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
httpPost.setHeader("Content-Type", "application/json;charset=utf8");

// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

有参(对象参数)

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
public static void doPost3() {
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// 创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/doPost3");
User user = new User();
user.setName("霍华德");
user.setAge(35);
user.setGender("男");
user.setMotto("扣篮要暴力~");

// 利用阿里的fastjson,将Object转换为json字符串;
// (需要导入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(user);

StringEntity entity = new StringEntity(jsonString, "UTF-8");

// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);

httpPost.setHeader("Content-Type", "application/json;charset=utf8");

// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

有参(普参+对参)

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
61
62
63
64
65
66
67
68
69
public static void doPost4(){
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();

// 创建Post请求
// 参数
URI uri = null;
try {
// 将参数放入键值对类NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("flag", "4"));
params.add(new BasicNameValuePair("meaning", "这是普通参数"));
// 设置uri信息,并将参数集合放入uri;
// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080)
.setPath("/doPost4").setParameters(params).build();
} catch (URISyntaxException e) {
e.printStackTrace();
}

HttpPost httpPost = new HttpPost(uri);

// 创建user参数
User user = new User();
user.setName("霍华德");
user.setAge(35);
user.setGender("男");
user.setMotto("扣篮要暴力~");

// 将user对象转换为json字符串,并放入entity中
StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");

// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);

httpPost.setHeader("Content-Type", "application/json;charset=utf8");

// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求3
response = httpClient.execute(httpPost);
System.out.println("响应状态为:" + response.getStatusLine());

// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();

if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
//释放实体资源
EntityUtils.consume(responseEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}