1 package com.example.demo.util.httpRequest;
2
3 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
4 import org.apache.http.HttpResponse;
5 import org.apache.http.NameValuePair;
6 import org.apache.http.client.HttpClient;
7 import org.apache.http.client.entity.UrlEncodedFormEntity;
8 import org.apache.http.client.methods.HttpDelete;
9 import org.apache.http.client.methods.HttpGet;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.client.methods.HttpPut;
12 import org.apache.http.conn.ClientConnectionManager;
13 import org.apache.http.conn.scheme.Scheme;
14 import org.apache.http.conn.scheme.SchemeRegistry;
15 import org.apache.http.conn.ssl.SSLSocketFactory;
16 import org.apache.http.entity.ByteArrayEntity;
17 import org.apache.http.entity.StringEntity;
18 import org.apache.http.impl.client.DefaultHttpClient;
19 import org.apache.http.message.BasicNameValuePair;
20
21 import javax.net.ssl.SSLContext;
22 import javax.net.ssl.TrustManager;
23 import javax.net.ssl.X509TrustManager;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URLEncoder;
26 import java.security.KeyManagementException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Map;
32
33 public class HttpUtils {
34
35 /**
36 * get
37 *
38 * @param host
39 * @param path
40 * @param method
41 * @param headers
42 * @param querys
43 * @return
44 * @throws Exception
45 */
46 public static HttpResponse doGet(String host, String path, String method,
47 Map<String, String> headers,
48 Map<String, String> querys)
49 throws Exception {
50 HttpClient httpClient = wrapClient(host);
51
52 HttpGet request = new HttpGet(buildUrl(host, path, querys));
53 for (Map.Entry<String, String> e : headers.entrySet()) {
54 request.addHeader(e.getKey(), e.getValue());
55 }
56
57 return httpClient.execute(request);
58 }
59
60 /**
61 * post form
62 *
63 * @param host
64 * @param path
65 * @param method
66 * @param headers
67 * @param querys
68 * @param bodys
69 * @return
70 * @throws Exception
71 */
72 public static HttpResponse doPost(String host, String path, String method,
73 Map<String, String> headers,
74 Map<String, String> querys,
75 Map<String, String> bodys)
76 throws Exception {
77 HttpClient httpClient = wrapClient(host);
78
79 HttpPost request = new HttpPost(buildUrl(host, path, querys));
80 for (Map.Entry<String, String> e : headers.entrySet()) {
81 request.addHeader(e.getKey(), e.getValue());
82 }
83
84 if (bodys != null) {
85 List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
86
87 for (String key : bodys.keySet()) {
88 nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
89 }
90 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
91 formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
92 request.setEntity(formEntity);
93 }
94
95 return httpClient.execute(request);
96 }
97
98 /**
99 * Post String
100 *
101 * @param host
102 * @param path
103 * @param method
104 * @param headers
105 * @param querys
106 * @param body
107 * @return
108 * @throws Exception
109 */
110 public static HttpResponse doPost(String host, String path, String method,
111 Map<String, String> headers,
112 Map<String, String> querys,
113 String body)
114 throws Exception {
115 HttpClient httpClient = wrapClient(host);
116
117 HttpPost request = new HttpPost(buildUrl(host, path, querys));
118 for (Map.Entry<String, String> e : headers.entrySet()) {
119 request.addHeader(e.getKey(), e.getValue());
120 }
121
122 if (StringUtils.isNotBlank(body)) {
123 request.setEntity(new StringEntity(body, "utf-8"));
124 }
125
126 return httpClient.execute(request);
127 }
128
129 /**
130 * Post stream
131 *
132 * @param host
133 * @param path
134 * @param method
135 * @param headers
136 * @param querys
137 * @param body
138 * @return
139 * @throws Exception
140 */
141 public static HttpResponse doPost(String host, String path, String method,
142 Map<String, String> headers,
143 Map<String, String> querys,
144 byte[] body)
145 throws Exception {
146 HttpClient httpClient = wrapClient(host);
147
148 HttpPost request = new HttpPost(buildUrl(host, path, querys));
149 for (Map.Entry<String, String> e : headers.entrySet()) {
150 request.addHeader(e.getKey(), e.getValue());
151 }
152
153 if (body != null) {
154 request.setEntity(new ByteArrayEntity(body));
155 }
156
157 return httpClient.execute(request);
158 }
159
160 /**
161 * Put String
162 * @param host
163 * @param path
164 * @param method
165 * @param headers
166 * @param querys
167 * @param body
168 * @return
169 * @throws Exception
170 */
171 public static HttpResponse doPut(String host, String path, String method,
172 Map<String, String> headers,
173 Map<String, String> querys,
174 String body)
175 throws Exception {
176 HttpClient httpClient = wrapClient(host);
177
178 HttpPut request = new HttpPut(buildUrl(host, path, querys));
179 for (Map.Entry<String, String> e : headers.entrySet()) {
180 request.addHeader(e.getKey(), e.getValue());
181 }
182
183 if (StringUtils.isNotBlank(body)) {
184 request.setEntity(new StringEntity(body, "utf-8"));
185 }
186
187 return httpClient.execute(request);
188 }
189
190 /**
191 * Put stream
192 * @param host
193 * @param path
194 * @param method
195 * @param headers
196 * @param querys
197 * @param body
198 * @return
199 * @throws Exception
200 */
201 public static HttpResponse doPut(String host, String path, String method,
202 Map<String, String> headers,
203 Map<String, String> querys,
204 byte[] body)
205 throws Exception {
206 HttpClient httpClient = wrapClient(host);
207
208 HttpPut request = new HttpPut(buildUrl(host, path, querys));
209 for (Map.Entry<String, String> e : headers.entrySet()) {
210 request.addHeader(e.getKey(), e.getValue());
211 }
212
213 if (body != null) {
214 request.setEntity(new ByteArrayEntity(body));
215 }
216
217 return httpClient.execute(request);
218 }
219
220 /**
221 * Delete
222 *
223 * @param host
224 * @param path
225 * @param method
226 * @param headers
227 * @param querys
228 * @return
229 * @throws Exception
230 */
231 public static HttpResponse doDelete(String host, String path, String method,
232 Map<String, String> headers,
233 Map<String, String> querys)
234 throws Exception {
235 HttpClient httpClient = wrapClient(host);
236
237 HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
238 for (Map.Entry<String, String> e : headers.entrySet()) {
239 request.addHeader(e.getKey(), e.getValue());
240 }
241
242 return httpClient.execute(request);
243 }
244
245 private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
246 StringBuilder sbUrl = new StringBuilder();
247 sbUrl.append(host);
248 if (!StringUtils.isBlank(path)) {
249 sbUrl.append(path);
250 }
251 if (null != querys) {
252 StringBuilder sbQuery = new StringBuilder();
253 for (Map.Entry<String, String> query : querys.entrySet()) {
254 if (0 < sbQuery.length()) {
255 sbQuery.append("&");
256 }
257 if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
258 sbQuery.append(query.getValue());
259 }
260 if (!StringUtils.isBlank(query.getKey())) {
261 sbQuery.append(query.getKey());
262 if (!StringUtils.isBlank(query.getValue())) {
263 sbQuery.append("=");
264 sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
265 }
266 }
267 }
268 if (0 < sbQuery.length()) {
269 sbUrl.append("?").append(sbQuery);
270 }
271 }
272
273 return sbUrl.toString();
274 }
275
276 private static HttpClient wrapClient(String host) {
277 HttpClient httpClient = new DefaultHttpClient();
278 if (host.startsWith("https://")) {
279 sslClient(httpClient);
280 }
281
282 return httpClient;
283 }
284
285 private static void sslClient(HttpClient httpClient) {
286 try {
287 SSLContext ctx = SSLContext.getInstance("TLS");
288 X509TrustManager tm = new X509TrustManager() {
289 @Override
290 public X509Certificate[] getAcceptedIssuers() {
291 return null;
292 }
293 @Override
294 public void checkClientTrusted(X509Certificate[] xcs, String str) {
295
296 }
297 @Override
298 public void checkServerTrusted(X509Certificate[] xcs, String str) {
299
300 }
301 };
302 ctx.init(null, new TrustManager[] { tm }, null);
303 SSLSocketFactory ssf = new SSLSocketFactory(ctx);
304 ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
305 ClientConnectionManager ccm = httpClient.getConnectionManager();
306 SchemeRegistry registry = ccm.getSchemeRegistry();
307 registry.register(new Scheme("https", 443, ssf));
308 } catch (KeyManagementException ex) {
309 throw new RuntimeException(ex);
310 } catch (NoSuchAlgorithmException ex) {
311 throw new RuntimeException(ex);
312 }
313 }
314 }
使用示例:
//高德地图api调用URL
String url = "https://restapi.amap.com/v3/config/district";
//封装入参
HashMap<String, String> param = new HashMap<>();
param.put("keywords", "安徽省");
param.put("subdistrict", "2");
//个人秘钥
param.put("key", "*****");
HttpResponse response = null;
String s = null;
try {
response = HttpUtils.doGet(url, null, null, new HashMap<>(), param);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (Exception e) {
log.error("三方接口调用失败或数据解析异常: {}" + e.getMessage());
return;
}
Op op = JSON.parseObject(result, Op.class);