xuhy
2025-01-09 b9009a5abd3f4129784a8d5e5316622e95669b68
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
package com.stylefeng.guns.modular.system.util;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.NameValuePair;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
 
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
/**
 * http工具类
 */
@Component
public class HttpClientUtil {
 
    private CloseableHttpClient httpClient;
 
    private CloseableHttpResponse httpResponse;
 
    private RequestConfig requestConfig;
 
 
    /**
     * 创建一个httpClient对象
     */
    private void getHttpCline(){
        //1.创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(60000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(1000);
        connectionManager.setDefaultMaxPerRoute(50);
 
        //2.创建httpclient对象
        this.httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .disableAutomaticRetries()
                .build();
    }
 
    private RequestConfig getRequestConfig(){
        return RequestConfig.custom()
                .setConnectTimeout(60000)
                .setSocketTimeout(60000)
                .build();
    }
 
 
 
    /**
     * 创建一个POST请求实例
     * @param url       请求地址
     * @param params    请求参数
     */
    private void setPostHttpRequset(String url, Map<String, Object> params, Map<String, String> header, String contentType){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.getRequestConfig());
        if(null != header){
            for(String key : header.keySet()){
                httpPost.setHeader(key, header.get(key));
            }
        }
        List<NameValuePair> list = new ArrayList<>();
        if(null != params){
            Set<String> keys = params.keySet();
            for(String key : keys){
                list.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
        }
        try {
            switch (contentType){
                case "form":
                    httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    break;
                case "json":
                    ObjectMapper objectMapper = new ObjectMapper();
                    String s =objectMapper.writeValueAsString(params);
                    System.err.println(s);
                    httpPost.setEntity(new StringEntity(s, Charset.forName("UTF-8")));
                    break;
            }
            this.getHttpCline();
            if(null == this.httpClient){
                this.getHttpCline();
            }
            httpResponse = this.httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            this.close();
        }
    }
 
 
    /**
     * 获取get请求实例
     * @param url       请求地址
     * @param params    请求参数
     */
    private void setGetHttpRequset(String url, Map<String, Object> params, Map<String, String> header){
        StringBuffer sb = new StringBuffer();
        String p = "";
        if(null != params){
            Set<String> keys = params.keySet();
            for(String key : keys){
                sb.append(key + "=" + params.get(key) + "&");
            }
            p = "?" + sb.substring(0, sb.length() - 1);
        }
        HttpGet httpGet = new HttpGet(url + p);
        if(null != header){
            for(String key : header.keySet()){
                httpGet.setHeader(key, header.get(key));
            }
        }
        this.getHttpCline();
        if(null == this.httpClient){
            this.getHttpCline();
        }
        try {
            httpResponse = this.httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
            this.close();
        }
    }
 
 
    /**
     * 发送http请求
     * @param mothed        "GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS"
     * @param url           请求地址
     * @param params        请求参数
     * @param header        请求头
     * @param contentType   参数请求方式form/json
     * @return
     */
    public String pushHttpRequset(String mothed, String url, Map<String, Object> params, Map<String, String> header, String contentType){
        String content = null;
        switch (mothed){
            case "GET":
                this.setGetHttpRequset(url, params, header);
                break;
            case "POST":
                this.setPostHttpRequset(url, params, header, contentType);
                break;
        }
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            try {
                content = EntityUtils.toString(httpResponse.getEntity());
                this.close();
                return content;
            } catch (IOException e) {
                e.printStackTrace();
                this.close();
            }
        }
        if(httpResponse.getStatusLine().getStatusCode() == 201){
            content = "{\"status\":201}";
            this.close();
            return content;
        }else{
            try {
                System.err.println("返回状态码:" + httpResponse.getStatusLine() + "。");
                content = EntityUtils.toString(httpResponse.getEntity());
                this.close();
                return content;
            } catch (IOException e) {
                e.printStackTrace();
                this.close();
            }
        }
        this.close();
        return content;
    }
 
 
    /**
     * 发送XML请求
     * @param url       请求地址
     * @param xml       XML数据
     * @param header    自定义请求头
     * @return
     */
    public String pushHttpRequsetXml(String url, String xml, Map<String, String> header){
        HttpPost httpPost = new HttpPost(url);
        for(String key : header.keySet()){
            httpPost.setHeader(key, header.get(key));
        }
        httpPost.setHeader("Content-Type", "application/xml");
        try {
            httpPost.setEntity(new StringEntity(xml, "UTF-8"));
            this.getHttpCline();
            if(null == this.httpClient){
                this.getHttpCline();
            }
            httpResponse = this.httpClient.execute(httpPost);
            String content = null;
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                try {
                    content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                    this.close();
                    return content;
                } catch (IOException e) {
                    e.printStackTrace();
                    this.close();
                }
            }else{
                try {
                    content = "返回状态码:" + httpResponse.getStatusLine() + "。" + EntityUtils.toString(httpResponse.getEntity());
                    this.close();
                    return content;
                } catch (IOException e) {
                    e.printStackTrace();
                    this.close();
                }
            }
            this.close();
            return content;
        } catch (IOException e) {
            e.printStackTrace();
            this.close();
        }
        return null;
    }
 
 
 
    /**
     * 请求https发送XML请求
     * @param url           接口路径
     * @param xml           内容
     * @param header        请求头
     * @param certPassword      证书密码
     * @param certPath      证书路径
     * @param certType      证书类型
     * @return
     * @throws Exception
     */
    public String pushHttpsRequsetXml(String url, String xml, Map<String, String> header, String certPassword, String certPath, String certType) throws Exception{
        HttpPost httpPost = new HttpPost(url);
        for(String key : header.keySet()){
            httpPost.setHeader(key, header.get(key));
        }
        httpPost.setHeader("Content-Type", "application/xml");
        try {
            httpPost.setEntity(new StringEntity(xml, "UTF-8"));
            this.getHttpCline();
            this.initCert(certPassword, certPath, certType);
            httpResponse = this.httpClient.execute(httpPost);
            String content = null;
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                try {
                    content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                    this.close();
                }
            }else{
                try {
                    content = "返回状态码:" + httpResponse.getStatusLine() + "。" + EntityUtils.toString(httpResponse.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                    this.close();
                }
            }
            this.close();
            return content;
        } catch (IOException e) {
            e.printStackTrace();
            this.close();
        }
        return null;
    }
 
 
    /**
     * 初始化https对象(带证书)
     * @param key       证书密码
     * @param certPath  证书路径
     * @param certType  证书类型
     * @throws Exception
     */
    private void initCert(String key, String certPath, String certType) throws Exception {
        KeyStore keyStore = KeyStore.getInstance(certType);
//        ClassPathResource cp = new ClassPathResource(certPath);
        InputStream inputStream = new FileInputStream(new File(certPath));
//        InputStream instream = cp.getInputStream();
        try {
            keyStore.load(inputStream, key.toCharArray());
        } finally {
            inputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
        SSLConnectionSocketFactory sslsf =
                new SSLConnectionSocketFactory(sslcontext, null, null,
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        this.httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }
 
 
    /**
     * 关闭资源
     */
    private void close(){
        try {
            if(null != httpClient){
                httpClient.close();
            }
            if(null != httpResponse){
                httpResponse.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != httpClient){
                    httpClient.close();
                }
                if(null != httpResponse){
                    httpResponse.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}