无关风月
2025-01-16 f0603f25dda4f57a1e5b508267384d7e2cb680ea
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package com.stylefeng.guns.modular.system.controller.util;
 
import com.aliyun.oss.ServiceException;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
public class HttpUtils {
 
    //请求超时时间
    private final static Integer TIME_OUT = 8 * 1000;
    //http连接池
    private static volatile PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
    //请求配置
    private static RequestConfig requestConfig;
 
    public static PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
        if (poolingHttpClientConnectionManager == null) {
            synchronized (HttpUtils.class) {
                if (poolingHttpClientConnectionManager == null) {
                    poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
                    //连接池最大连接数
                    poolingHttpClientConnectionManager.setMaxTotal(1024);
                    //每个路由最大连接数
                    poolingHttpClientConnectionManager.setDefaultMaxPerRoute(32);
 
                    //配置请求的超时设置
                    requestConfig =
                            RequestConfig.custom().setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build();
                }
            }
        }
        return poolingHttpClientConnectionManager;
    }
 
    public static CloseableHttpClient getHttpClient() {
        return HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).setDefaultRequestConfig(requestConfig).build();
    }
 
    /**
     * 请求发送执行
     *
     * @param httpMethd
     * @return
     */
    public static String registRequest(HttpUriRequest httpMethd) {
        CloseableHttpClient httpClient = getHttpClient();
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpMethd, HttpClientContext.create())) {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                httpMethd.abort();
            }
            String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
            return response;
        } catch (Exception e) {
            throw new RuntimeException("请求失败", e);
        }
    }
 
    public static List<BasicNameValuePair> toPairs(Map<String, Object> params) {
        List<BasicNameValuePair> pairs = new ArrayList<>(params.size());
        if (params != null && !params.isEmpty()) {
            pairs = params.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(),
                    entry.getValue().toString())).collect(Collectors.toList());
        }
        return pairs;
    }
 
    /**
     * get url请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        HttpGet request = new HttpGet();
        try {
            request.setURI(new URI(url));
            return registRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /***
     * get请求(带参数)
     * @param url
     * @return String
     */
    public static String getReq(String url, Map<String, String> params) {
        String result = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            Iterator maplist = params.entrySet().iterator();
            while (maplist.hasNext()) {
                Map.Entry<String, String> map = (Map.Entry<String, String>) maplist.next();
                uriBuilder.addParameter(map.getKey(), map.getValue());
            }
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(uriBuilder.build());
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            HttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
 
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
 
    /***
     * get请求(带参数)
     * @param url
     * @return String
     */
    public static String postReq(String url, Map<String, Object> params,String token) {
        String result = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            Iterator maplist = params.entrySet().iterator();
            while (maplist.hasNext()) {
                Map.Entry<String, Object> map = (Map.Entry<String, Object>) maplist.next();
                uriBuilder.addParameter(map.getKey(), String.valueOf(map.getValue()));
            }
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(uriBuilder.build());
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            post.addHeader("Content-type", "application/json");
            post.addHeader("Accept", "application/json");
            post.addHeader("Authorization", token);
            HttpResponse response = client.execute(post);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
 
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
 
    /**
     * PSOT URL方式提交
     *
     * @param url    请求url
     * @param params 请求参数
     * @return
     */
    public static String postFromUrl(String url, Map<String, Object> params) {
        HttpPost request = new HttpPost(url);
        request.setEntity(new UrlEncodedFormEntity(toPairs(params), Consts.UTF_8));
        try {
            return registRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * PSOT JSON方式提交
     *
     * @param url    请求url
     * @param params json串
     * @return
     */
    public static String postFromJson(String url, String params,String token) {
        HttpPost request = new HttpPost(url);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Accept", "application/json");
        request.setHeader("Authorization", token);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(8000)
                .setConnectTimeout(6000)
                .build();
        request.setConfig(requestConfig);
        StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        request.setEntity(entity);
        try {
            return registRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * PSOT JSON方式提交
     *
     * @param url    请求url
     * @param params json串
     * @return
     */
    public static String postFromJson(String url, String params) {
        HttpPost request = new HttpPost(url);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Accept", "application/json");
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(8000)
                .setConnectTimeout(6000)
                .build();
        request.setConfig(requestConfig);
        StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        request.setEntity(entity);
        try {
            return registRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * post请求带token
     * @param strURL
     * @param params
     * @param token
     * @return
     */
    public static String post(String strURL, String params, String token) {
        String result = "";
        BufferedReader reader = null;
        try {
            System.out.println(strURL);
            System.out.println(params);
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json;charset=utf-8"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式
            connection.setRequestProperty("Authorization", token); // 设置token
            connection.connect();
            if (params != null && !TextUtils.isEmpty(params)) {
                byte[] writebytes = params.getBytes();
                // 设置文件长度
                //   connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = connection.getOutputStream();
                outwritestream.write(params.getBytes());
                outwritestream.flush();
                outwritestream.close();
                // Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
            }
            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            } else {
                throw new ServiceException(connection.getResponseMessage());
            }
        } catch (Exception e) {
            throw new ServiceException("http的post请求异常!" + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
 
    /**
     * post请求
     * @param strURL
     * @param params
     * @return
     */
    public static String post(String strURL, String params) {
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json;charset=utf-8"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式
            connection.connect();
            if (params != null && !TextUtils.isEmpty(params)) {
                byte[] writebytes = params.getBytes();
                // 设置文件长度
                //   connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = connection.getOutputStream();
                outwritestream.write(params.getBytes());
                outwritestream.flush();
                outwritestream.close();
                // Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
            }
            if (connection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
            } else {
                throw new ServiceException(connection.getResponseMessage());
            }
        } catch (Exception e) {
            throw new ServiceException("http的post请求异常!" + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}