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
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
package cn.autoform.web.client.util;
 
import cn.autoform.util.thread.ThreadData;
import cn.autoform.util.tool.JSONTool;
import cn.autoform.web.client.conster.BaseConst;
import cn.autoform.web.interceptor.spring.InitParamInterceptor;
import com.alibaba.fastjson.TypeReference;
import com.codingapi.tx.aop.bean.TxTransactionLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.conn.HttpHostConnectException;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeoutException;
 
/**
 * @ClassName: HttpClientTool
 * @Description: TODO[后台发送请求工具类]
 * @author [九鼎联合科技]
 * @date 2017年2月27日 下午5:19:57
 */
@Slf4j
public class HttpClientTool<T> extends TypeReference<T>{
    
    public static final String COOKIE_KEY = "Cookie";
    
    public static final String APPLICATION_JSON = "application/json;charset=utf-8";
    /**
     * 访问url
     */
    private String url;
    
    private CloseableHttpClient httpClient;
    
    private Map<String, Object> params;
    
    private HttpEntity bodyInfos;
    
    private Map<String, ? extends Object> cookie;
    
    private RequestConfig requestConfig;
    
    
    public HttpClientTool(String url) {
        this.url = url;
        this.httpClient = HttpClients.createDefault();
        log.debug("初始化:{}", url);
        // 添加cookie
        Map<String, Object> cookie = new HashMap<>();
        InitParamInterceptor.COOKIE_KEY.entrySet().stream()
        .filter(cookieKey->{
            return StringUtils.isNoneBlank(Objects.toString(ThreadData.get(cookieKey.getValue()), ""));
        })
        .forEach(cookieKey->{
            log.debug("当前添加:{},{}", cookieKey.getKey(),ThreadData.get(cookieKey.getValue()));
            cookie.put(cookieKey.getKey(), ThreadData.get(cookieKey.getValue()));
        });
        this.cookie = cookie;
    }
    
    public HttpClientTool() {
        
    }
    
 
    /**
     * get请求待更新
     * @Title: sendGet
     
     * @param @param requestJson
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public T sendGet(){
        HttpGet httpGet = new HttpGet(url);
        if(null != requestConfig)
            httpGet.setConfig(requestConfig);
        try {
            HttpResponse response = this.httpClient.execute(httpGet);
            return httpEntityToStr(response.getEntity());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    
    
    /**
     * @throws TimeoutException 
     * 发送post请求
     * @Title: sendPost
     
     * @param @param requestJson
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public T sendPost(ResultFormat<T> rf) throws TimeoutException{
        log.debug("开始发送post请求:{}", url);
        HttpPost httpPost = new HttpPost(url);
        setHttpEntity(httpPost);
//        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50000)
//                .setConnectionRequestTimeout(10000).setSocketTimeout(50000).build();
        addHeader(httpPost);
        if(null != requestConfig)
            httpPost.setConfig(requestConfig);
        
        try {
            long begin = System.currentTimeMillis();
            HttpResponse response = this.httpClient.execute(httpPost);
            log.debug("请求时间{}", (System.currentTimeMillis() - begin));
            String res;
            T obj = rf.format(res = EntityUtils.toString(response.getEntity(), BaseConst.PROJECT_CHARSET));
//            obj = httpEntityToStr(response.getEntity());
            log.debug("响应返回值为:{}", res);
            
            return obj;
    
        }catch (HttpHostConnectException hhe){
            log.error(hhe.getMessage(), hhe);
            throw new TimeoutException(hhe.getMessage());
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new TimeoutException(e.getMessage());
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void addHeader(HttpPost httpPost) {
 
        TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
        String groupId = txTransactionLocal == null ? null : txTransactionLocal.getGroupId();
 
        log.info("LCN-SpringCloud TxGroup info -> groupId:"+groupId);
 
        if(txTransactionLocal!=null) {
                httpPost.setHeader("tx-group", groupId);
        }
        if(null != cookie) {
            httpPost.setHeader(COOKIE_KEY, mapToStrByCookie(cookie));
        }
    }
    
    public static interface ResultFormat<T>{
        
        T format(String json);
        
    }
    
    // HttpAgent
    public  HttpResponse httpAgent() throws Exception {  
        // 创建HttpClientBuilder  
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
        // HttpClient  
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
        // 依次是目标请求地址,端口号,协议类型  
        HttpHost target = new HttpHost(url);
        // 依次是代理地址,代理端口号,协议类型  
        HttpHost proxy = new HttpHost("10.4.32.59", 80, "http");  
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();  
  
        // 请求地址  
        HttpPost httpPost = new HttpPost(url);  
        setHttpEntity(httpPost);
        if(null != cookie)
            httpPost.setHeader(COOKIE_KEY, mapToStrByCookie(cookie));
        if(null != requestConfig)
            httpPost.setConfig(requestConfig);
        
        httpPost.setConfig(config);  
           
        //新加
        setHttpEntity(httpPost);
       log.debug("httpPost->"+httpPost);
       log.debug("bodyInfos->"+bodyInfos); 
           
           HttpResponse response = closeableHttpClient.execute(  
                    target, httpPost);  
            // getEntity()  
            log.debug("调试close前:"+response);
            closeableHttpClient.close(); 
            log.debug("调试close后:"+response);
            return response;
 
    }      
    
    /*
     * 获得httpEntity
     */
    private void setHttpEntity(HttpPost httpPost){
        if(bodyInfos == null) return;
        httpPost.setEntity(bodyInfos);
    }
    
    @SuppressWarnings({ "unchecked", "hiding" })
    private <T> T httpEntityToStr(HttpEntity httpEntity) throws InstantiationException, IllegalAccessException{
        log.debug("httpEntity.toString()"+httpEntity.toString());
        try {
            String json = EntityUtils.toString(httpEntity, BaseConst.PROJECT_CHARSET);
            return (T) JSONTool.toObj(json, this);
        } catch (ParseException | IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    private void setParam(){
        if(params == null || params.isEmpty()) 
            return ;
        StringBuilder paramStr = new StringBuilder();
        boolean isOne = true;
        for (Map.Entry<String, ? extends Object> entrys : this.params.entrySet()) {
            Object val = entrys.getValue();
            if(val != null){
                if(isOne){
                    paramStr.append('?');
                    isOne = false;
                }else{
                    paramStr.append('&');
                }
                if(val instanceof CharSequence || val instanceof Number){
                    paramStr.append(entrys.getKey()).append('=').append(URLTool.encoder(val.toString()));
                }else {
                    paramStr.append(entrys.getKey()).append('=').append(URLTool.encoder(JSONTool.toJson(val)));
                    
                }
            }
        }
        if(paramStr.length() != 0){
            this.url = paramStr.insert(0, url).toString();
        }
        
    }
 
    private String mapToStrByCookie(Map<String, ? extends Object> cookies){
        StringBuilder str = new StringBuilder();
        for (Map.Entry<String, ? extends Object> eachCookie : cookies.entrySet()) {
            if(str.length() == 0){
                str.append(eachCookie.getKey()).append('=').append(
                        eachCookie.getValue() instanceof String
                        ? 
                        eachCookie.getValue() 
                        :
                        JSONTool.toJson(eachCookie.getValue()));
            }else{
                str.append(';').append(eachCookie.getKey()).append('=').append(
                        eachCookie.getValue() instanceof String
                        ? 
                        eachCookie.getValue() 
                        :
                        JSONTool.toJson(eachCookie.getValue()));
            }
        }
        return str.toString();
    }
    
    public void setCookie(Map<String, ? extends Object> cookie) {
 
        this.cookie = cookie;
    }
 
    public Object getBodyInfos() {
        return bodyInfos;
    }
 
    public void setBodyInfos(Object param) {
        if(param instanceof HttpEntity){
            this.bodyInfos = (HttpEntity) param;
        }else{
            String p ;
            log.debug("参数:"+ (p = JSONTool.toJson(param)));
            StringEntity stringEntity = new StringEntity(p, BaseConst.PROJECT_CHARSET);
            stringEntity.setContentType(APPLICATION_JSON);
            this.bodyInfos = stringEntity;
        }
    }
    
    public static HttpEntity getUrlEntity(Map<String, Object> map){
        List<BasicNameValuePair> params=new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object val = entry.getValue();
            if(val != null){
                if(val instanceof Number || val instanceof CharSequence){
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }else{
                    params.add(new BasicNameValuePair(entry.getKey(), JSONTool.toJson(entry.getValue())));
                }
            }
        }
        try {
            return new UrlEncodedFormEntity(params, BaseConst.PROJECT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
 
    public Map<String,Object> getParams() {
        return params;
    }
 
    public void setParams(Map<String,Object> params) {
        this.params = params;
        setParam();
    }
 
    public RequestConfig getRequestConfig() {
        return requestConfig;
    }
 
    public void setRequestConfig(RequestConfig requestConfig) {
        this.requestConfig = requestConfig;
    }
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
    
}