puzhibing
2023-06-12 d4f8078c2a062864dab885d6bd54fbe1195f85e2
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
package com.stylefeng.guns.modular.system.controller.util;
 
import com.google.common.collect.Lists;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.conn.ConnectTimeoutException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
@Component
public class HttpUtils {
 
    private Logger log = LoggerFactory.getLogger(this.getClass());
 
    private final static String KEY = "7589cb21f09f6ab1a1263ca98f0b4d52";
 
    //请求超时时间
    private final static Integer TIME_OUT = 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 String registRequest(HttpUriRequest httpMethd) {
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpMethd, HttpClientContext.create());
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.error("响应失败 statusCode {}", statusCode);
                httpMethd.abort();
            }
            log.debug("响应成功 statusCode {}", statusCode);
            String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
            log.debug("响应成功 response {}", response);
            return response;
        } catch (ConnectTimeoutException e) {
            throw new RuntimeException("接口超时");
        } catch (SocketTimeoutException e) {
            throw new RuntimeException("读取接口数据超时");
        } catch (IOException e) {
            throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问");
        } finally {
            // 关闭响应
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                // 关闭连接
                //httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException("关闭流异常:IOException");
            }
        }
    }
 
    /**
     * 请求发送执行
     *
     * @param url
     * @return
     */
    public String registRequest(String url, File file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try  {
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(5000)
                .build();
        httpPost.setConfig(requestConfig);
        HttpEntity entity = MultipartEntityBuilder.create().addPart("img", new FileBody(file)).build();
        httpPost.setEntity(entity);
         httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.error("响应失败 statusCode {}", statusCode);
            httpPost.abort();
        }
        log.debug("响应成功 statusCode {}", statusCode);
        String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
        log.debug("响应成功 response {}", response);
        return response;
        } catch (ConnectTimeoutException e) {
            throw new RuntimeException("接口超时");
        } catch (SocketTimeoutException e) {
            throw new RuntimeException("读取接口数据超时");
        } catch (IOException e) {
            throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问");
        } finally {
            // 关闭响应
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                // 关闭连接
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException("关闭流异常:IOException");
            }
        }
    }
 
    /**
     *
     * @param type
     * @param file
     * @return
     * @throws Exception
     */
    public String ocr(String type, File file){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        // HttpClient请求的相关设置,可以不用配置,用默认的参数,这里设置连接和超时时长(毫秒)
        RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
        try {
            HttpPost httppost = new HttpPost("http://v.juhe.cn/certificates/query");
            // FileBody封装File类型的参数
            FileBody bin = new FileBody(file);
            // StringBody封装String类型的参数
            StringBody keyBody = new StringBody(KEY, ContentType.TEXT_PLAIN);
            StringBody typeBody = new StringBody(type, ContentType.TEXT_PLAIN);
            // addPart将参数传入,并指定参数名称
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("pic", bin).addPart("key", keyBody)
                    .addPart("cardType", typeBody).build();
            httppost.setEntity(reqEntity);
            httppost.setConfig(config);
            // 执行网络请求并返回结果
            response = httpClient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            }
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问"+":"+e);
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException("流关闭失败!"+":"+e);
            }
        }
        // 得到的是JSON类型的数据需要第三方解析JSON的jar包来解析
        return result;
    }
 
    // 此方法是把传进的字节流转化为相应的字符串并返回,此方法一般在网络请求中用到
    public static String ConvertStreamToString(InputStream is, String charset)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        try (InputStreamReader inputStreamReader = new InputStreamReader(is,charset)) {
            try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\r\n");
                }
            }
        }
        return sb.toString();
    }
 
    public List<BasicNameValuePair> toPairs(Map<String, Object> params) {
        List<BasicNameValuePair> pairs = Lists.newArrayList();
        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 String get(String url) {
        HttpGet request = new HttpGet();
        try {
            request.setURI(new URI(url));
            return registRequest(request);
        } catch (Exception e) {
            log.error("请求失败", e);
        }
        return null;
    }
 
    /**
     * PSOT URL方式提交
     *
     * @param url    请求url
     * @param params 请求参数
     * @return
     */
    public String postFromUrl(String url, Map<String, Object> params) {
        HttpPost request = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(5000)
                .build();
        request.setConfig(requestConfig);
        request.setEntity(new UrlEncodedFormEntity(toPairs(params), Consts.UTF_8));
        return registRequest(request);
    }
 
    /**
     * PSOT JSON方式提交
     *
     * @param url    请求url
     * @param params json串
     * @return
     */
    public 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) {
            log.error("请求失败", e);
        }
        return null;
    }
}