zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
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
 package com.changhong.epc.rely.api.tool;
 
import com.iemsoft.framework.cloud.core.constant.BaseConst;
import com.iemsoft.framework.cloud.core.tools.JSONTool;
import com.iemsoft.framework.cloud.core.tools.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
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.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.lang.reflect.Type;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeoutException;
 
/**
 * http请求工具类
 * @author liush
 *
 */
@Slf4j
public class HttpUtil {
    private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslsf = null;
    private static PoolingHttpClientConnectionManager cm = null;
    private static SSLContextBuilder builder = null;
    public static final String APPLICATION_JSON = "application/json;charset=utf-8";
    static {
        try {
            builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslsf)
                    .build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection
        } catch (Exception e) {
            // System.err.println(e.getMessage());
        }
    }
    
    public static <T> T get(String url, Map<String, String> header, Class<T> result) throws TimeoutException {
        try (CloseableHttpClient httpClient = url.startsWith("https") ? getHttpClient() : HttpClients.createDefault()){
            HttpGet httpGet = new HttpGet(url);
            // 设置头信息
            if (ObjectUtil.notEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                String str = EntityUtils.toString(resEntity, BaseConst.PROJECT_CHARSET);
                if(ObjectUtil.notEmpty(str)){
                    return JSONTool.toObj(str, result);
                }
                return null;
            } else {
                readHttpResponse(httpResponse);
                return null;
            }
        } catch (Exception e) {
            throw new TimeoutException();
        }
    }
    
    /**
     * httpClient post请求
     * @param url 请求url
     * @param header 头部信息
     * @param param 请求参数 form提交适用
     * @param body 请求实体 json/xml提交适用
     * @return 可能为空 需要处理
     * @throws Exception
     *
     */
    public static <T> T post(String  url, Map<String, String> header, Map<String, ? extends Object> param, Object body, Type type) throws Exception {
        String result = "";
        try (CloseableHttpClient httpClient = url.startsWith("https") ? getHttpClient() : HttpClients.createDefault()){
            log.debug("开始发送请求:{}", url);
            log.debug("header:{}", JSONTool.toJson(header));
            log.debug("body  :{}", JSONTool.toJson(body));
            log.debug("param :{}", JSONTool.toJson(param));
            HttpPost httpPost = new HttpPost(url);
            // 设置头信息
            if (ObjectUtil.notEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置请求参数
            if (ObjectUtil.notEmpty(param)) {
                List<NameValuePair> formparams = new ArrayList<>();
                for (Map.Entry<String, ? extends Object> entry : param.entrySet()) {
                    log.debug(JSONTool.toJson(entry));
                    //给参数赋值
                    Object o = null;
                    if(entry.getValue() instanceof String){
                        o = entry.getValue();
                    }else{
                        o = JSONTool.toJson(entry.getValue());
                    }
 
                    formparams.add(new BasicNameValuePair(entry.getKey(), Objects.toString(o, "")));
                }
                
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }
            // 设置实体 优先级高
            if (body != null) {
                StringEntity stringEntity = new StringEntity(JSONTool.toJson(body), BaseConst.PROJECT_CHARSET);
                stringEntity.setContentType(APPLICATION_JSON);
                httpPost.setEntity(stringEntity);
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
                log.debug("response:{}", result);
            } else {
                log.error("请求url:{}", url);
                log.error("response:{}", readHttpResponse(httpResponse));
            }
        } catch (Exception e) {
            throw e;
        }
        log.debug("返回:{}", result);
        // System.out.println(type);
        return JSONTool.toObj(result, type);
    }
    
 
    public static String getParam(Map<String, Object> param){
        if(ObjectUtil.empty(param)) return "";
        StringBuilder query = new StringBuilder();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            query.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
        }
        query.deleteCharAt(query.length()-1);
        return query.toString();
    }
    
    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .setConnectionManagerShared(true)
                .build();
        return httpClient;
    }
    public static String readHttpResponse(HttpResponse httpResponse)
            throws ParseException, IOException {
        StringBuilder builder = new StringBuilder();
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        builder.append("status:" + httpResponse.getStatusLine());
        builder.append("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            builder.append("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            builder.append("response length:" + responseString.length());
            builder.append("response content:" + responseString.replace("\r\n", ""));
        }
        return builder.toString();
    }
 
}