0%

HttpClient使用及工具类

文章字数:356,阅读全文大约需要1分钟

一、依赖

主要是两个包,发起连接的httpclient以及定义http请求数据类型的包httpmime

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependencies>
<!-- httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>

二、封装工具类

把常用的功能封装成工具类

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package org.colin;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.stream.Collectors;

/**
* httpClient常用功能封装
*/
public class HttpClientUtil {


/**
* 将http请求结果的内容读取成字符串
*
* @param response
* @return
* @throws IOException
*/
public static String parseRespToStr(CloseableHttpResponse response) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
response.getEntity().writeTo(outputStream);
return outputStream.toString();
}

/**
* 创建formData的httpPost请求
* content-type 对应 multipart/form-data
*
* @param url post地址
* @param headers 请求头内容
* @param params 表单内容 map,value支持 String/File/Collection<File>
* @return
* @throws IOException
*/
public static HttpPost createFormDataHttpPost(String url, Map<String, String> headers, Map<String, Object> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if(params != null) {
params.forEach((k,v)->{
if(v instanceof File) {
builder.addBinaryBody(k ,(File) v);
} else if(v instanceof Collection) {
for (Object obj : (Collection)v) {
builder.addBinaryBody(k, (File)obj);
}
} else {
builder.addTextBody(k, v.toString());
}
});
}
httpPost.setEntity(builder.build());
if(headers != null) {
headers.forEach(httpPost::addHeader);
}
return httpPost;
}

/**
* 创建纯字符串的form表单,并进行url编码
* content-type 对应 application/x-www-form-urlencoded
*
* @param url
* @param headers
* @param params
* @return
* @throws IOException
*/
public static HttpPost createFormUrlencodedHttpPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
List<BasicNameValuePair> nameValuePairs;
if(params != null) {
nameValuePairs = params.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
} else {
nameValuePairs = new LinkedList<>();
}
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httpPost.setEntity(entity);
if(headers != null) {
headers.forEach(httpPost::addHeader);
}
return httpPost;
}

/**
* 创建json格式的httpPost请求
* content-type 对应 application/json
*
* @param url
* @param headers
* @param jsonStr
* @return
* @throws UnsupportedEncodingException
*/
public static HttpPost createJsonHttpPost(String url, Map<String, String> headers, String jsonStr) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jsonStr));
if(headers != null) {
headers.forEach(httpPost::addHeader);
}
return httpPost;
}

/**
* 创建httpGet请求
*
* @param url
* @param headers
* @return
* @throws IOException
*/
public static HttpGet createHttpGet(String url, Map<String, String> headers) throws IOException {
HttpGet httpGet = new HttpGet(url);
if(headers != null) {
headers.forEach(httpGet::addHeader);
}
return httpGet;
}

public static HttpClientBuilder getHttpClientBuilder() {
return HttpClientBuilder.create();
}

public static HttpClientBuilder getHttpsClientBuilder() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
return HttpClientBuilder.create().setSSLContext(ctx);
}
}

三、测试类

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
70
71
72
73
74
75
76
package com.colin;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class Test {
public static void main( String[] args ) throws UnsupportedEncodingException {
HttpClientUtil app = new HttpClientUtil();
try {
String url = "http://127.0.0.1:8098/test";
// 复用一个httpClient
CloseableHttpClient client = HttpClientBuilder.create().build();
// 1. get请求测试
HttpGet get = app.createHttpGet(url + "?name=111&age=333", null);

// 2. post请求测试 application/x-www-form-urlencoded
Map<String, String> param = new HashMap<>();
param.put("name", "321");
param.put("age", "10");
HttpPost postStr = app.createFormUrlencodedHttpPost(url, param, param);

// 3. post请求测试,多文件上传 multipart/form-data
Map<String, Object> params = new HashMap<>();
params.put("name", "123");
params.put("age", "10");
LinkedList<Object> list = new LinkedList<>();
list.add(new File("E:\\321.png"));
list.add(new File("E:\\123.png"));
params.put("photo", list);
HttpPost postFormData1 = app.createFormDataHttpPost(url, null, params);

// 4. post请求测试,单文件上传 multipart/form-data
params = new HashMap<>();
params.put("name", "123");
params.put("age", "10");
params.put("photo", new File("E:\\321.png"));
HttpPost postFormData2 = app.createFormDataHttpPost(url, null, params);

// 5. post请求测试,json格式 application/json
HashMap<String, String> head = new HashMap<>();
HttpPost postJson = app.createJsonHttpPost("http://127.0.0.1:8098/jsonTest", head, "{'name':'123', 'age':'333'}");

// 发起请求
CloseableHttpResponse response;
response = client.execute(get);
System.out.println("-------get---------");
System.out.println(HttpClientUtil.parseRespToStr(response));

response = client.execute(postStr);
System.out.println("---------post str----------");
System.out.println(HttpClientUtil.parseRespToStr(response));

response = client.execute(postFormData1);
System.out.println("---------post formData1----------");
System.out.println(HttpClientUtil.parseRespToStr(response));

response = client.execute(postFormData2);
System.out.println("---------post formData2----------");
System.out.println(HttpClientUtil.parseRespToStr(response));

response = client.execute(postJson);
System.out.println("---------post json----------");
System.out.println(HttpClientUtil.parseRespToStr(response));
} catch (Exception 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
@GetMapping("/test")
@ResponseBody
String getTest(String name, String age){
System.out.println("name = " + name);
System.out.println("age = " + age);
return "getOk";
}

// 兼容接收多个文件,或者一个
@PostMapping("/test")
@ResponseBody
String postTest(String name, String age, @RequestParam(value = "photo", required = false) MultipartFile[] photo) {
System.out.println("name = " + name);
System.out.println("age = " + age);
if(photo != null) {
for (MultipartFile file : photo) {
System.out.println("photo.getSize() = " + file.getSize());
System.out.println("photo.getName() = " + file.getOriginalFilename());
}
}
return "postOk";
}

@PostMapping("/jsonTest")
@ResponseBody
String jsonTest(@RequestBody String json) {
System.out.println("json = " + json);
return "postOk";
}