commit | author | age
|
a18bfa
|
1 |
package cn.autoform.web.client.util; |
Z |
2 |
|
|
3 |
import cn.autoform.util.thread.ThreadData; |
|
4 |
import cn.autoform.util.tool.JSONTool; |
|
5 |
import cn.autoform.web.client.conster.BaseConst; |
|
6 |
import cn.autoform.web.interceptor.spring.InitParamInterceptor; |
|
7 |
import com.alibaba.fastjson.TypeReference; |
|
8 |
import com.codingapi.tx.aop.bean.TxTransactionLocal; |
|
9 |
import lombok.extern.slf4j.Slf4j; |
|
10 |
import org.apache.commons.lang3.StringUtils; |
|
11 |
import org.apache.http.HttpEntity; |
|
12 |
import org.apache.http.HttpHost; |
|
13 |
import org.apache.http.HttpResponse; |
|
14 |
import org.apache.http.ParseException; |
|
15 |
import org.apache.http.client.HttpClient; |
|
16 |
import org.apache.http.client.config.RequestConfig; |
|
17 |
import org.apache.http.client.entity.UrlEncodedFormEntity; |
|
18 |
import org.apache.http.client.methods.HttpGet; |
|
19 |
import org.apache.http.client.methods.HttpPost; |
|
20 |
import org.apache.http.conn.HttpHostConnectException; |
|
21 |
import org.apache.http.entity.StringEntity; |
|
22 |
import org.apache.http.impl.client.CloseableHttpClient; |
|
23 |
import org.apache.http.impl.client.HttpClientBuilder; |
|
24 |
import org.apache.http.impl.client.HttpClients; |
|
25 |
import org.apache.http.message.BasicNameValuePair; |
|
26 |
import org.apache.http.util.EntityUtils; |
|
27 |
|
|
28 |
import java.io.IOException; |
|
29 |
import java.io.UnsupportedEncodingException; |
|
30 |
import java.util.*; |
|
31 |
import java.util.concurrent.TimeoutException; |
|
32 |
|
|
33 |
/** |
|
34 |
* @ClassName: HttpClientTool |
|
35 |
* @Description: TODO[后台发送请求工具类] |
|
36 |
* @author [九鼎联合科技] |
|
37 |
* @date 2017年2月27日 下午5:19:57 |
|
38 |
*/ |
|
39 |
@Slf4j |
|
40 |
public class HttpClientTool<T> extends TypeReference<T>{ |
|
41 |
|
|
42 |
public static final String COOKIE_KEY = "Cookie"; |
|
43 |
|
|
44 |
public static final String APPLICATION_JSON = "application/json;charset=utf-8"; |
|
45 |
/** |
|
46 |
* 访问url |
|
47 |
*/ |
|
48 |
private String url; |
|
49 |
|
|
50 |
private CloseableHttpClient httpClient; |
|
51 |
|
|
52 |
private Map<String, Object> params; |
|
53 |
|
|
54 |
private HttpEntity bodyInfos; |
|
55 |
|
|
56 |
private Map<String, ? extends Object> cookie; |
|
57 |
|
|
58 |
private RequestConfig requestConfig; |
|
59 |
|
|
60 |
|
|
61 |
public HttpClientTool(String url) { |
|
62 |
this.url = url; |
|
63 |
this.httpClient = HttpClients.createDefault(); |
|
64 |
log.debug("初始化:{}", url); |
|
65 |
// 添加cookie |
|
66 |
Map<String, Object> cookie = new HashMap<>(); |
|
67 |
InitParamInterceptor.COOKIE_KEY.entrySet().stream() |
|
68 |
.filter(cookieKey->{ |
|
69 |
return StringUtils.isNoneBlank(Objects.toString(ThreadData.get(cookieKey.getValue()), "")); |
|
70 |
}) |
|
71 |
.forEach(cookieKey->{ |
|
72 |
log.debug("当前添加:{},{}", cookieKey.getKey(),ThreadData.get(cookieKey.getValue())); |
|
73 |
cookie.put(cookieKey.getKey(), ThreadData.get(cookieKey.getValue())); |
|
74 |
}); |
|
75 |
this.cookie = cookie; |
|
76 |
} |
|
77 |
|
|
78 |
public HttpClientTool() { |
|
79 |
|
|
80 |
} |
|
81 |
|
|
82 |
|
|
83 |
/** |
|
84 |
* get请求待更新 |
|
85 |
* @Title: sendGet |
|
86 |
|
|
87 |
* @param @param requestJson |
|
88 |
* @param @return 设定文件 |
|
89 |
* @return String 返回类型 |
|
90 |
* @throws |
|
91 |
*/ |
|
92 |
public T sendGet(){ |
|
93 |
HttpGet httpGet = new HttpGet(url); |
|
94 |
if(null != requestConfig) |
|
95 |
httpGet.setConfig(requestConfig); |
|
96 |
try { |
|
97 |
HttpResponse response = this.httpClient.execute(httpGet); |
|
98 |
return httpEntityToStr(response.getEntity()); |
|
99 |
} catch (Exception e) { |
|
100 |
log.error(e.getMessage(), e); |
|
101 |
return null; |
|
102 |
} |
|
103 |
} |
|
104 |
|
|
105 |
|
|
106 |
/** |
|
107 |
* @throws TimeoutException |
|
108 |
* 发送post请求 |
|
109 |
* @Title: sendPost |
|
110 |
|
|
111 |
* @param @param requestJson |
|
112 |
* @param @return 设定文件 |
|
113 |
* @return String 返回类型 |
|
114 |
* @throws |
|
115 |
*/ |
|
116 |
public T sendPost(ResultFormat<T> rf) throws TimeoutException{ |
|
117 |
log.debug("开始发送post请求:{}", url); |
|
118 |
HttpPost httpPost = new HttpPost(url); |
|
119 |
setHttpEntity(httpPost); |
|
120 |
// RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50000) |
|
121 |
// .setConnectionRequestTimeout(10000).setSocketTimeout(50000).build(); |
|
122 |
addHeader(httpPost); |
|
123 |
if(null != requestConfig) |
|
124 |
httpPost.setConfig(requestConfig); |
|
125 |
|
|
126 |
try { |
|
127 |
long begin = System.currentTimeMillis(); |
|
128 |
HttpResponse response = this.httpClient.execute(httpPost); |
|
129 |
log.debug("请求时间{}", (System.currentTimeMillis() - begin)); |
|
130 |
String res; |
|
131 |
T obj = rf.format(res = EntityUtils.toString(response.getEntity(), BaseConst.PROJECT_CHARSET)); |
|
132 |
// obj = httpEntityToStr(response.getEntity()); |
|
133 |
log.debug("响应返回值为:{}", res); |
|
134 |
|
|
135 |
return obj; |
|
136 |
|
|
137 |
}catch (HttpHostConnectException hhe){ |
|
138 |
log.error(hhe.getMessage(), hhe); |
|
139 |
throw new TimeoutException(hhe.getMessage()); |
|
140 |
}catch (Exception e) { |
|
141 |
log.error(e.getMessage(), e); |
|
142 |
throw new TimeoutException(e.getMessage()); |
|
143 |
}finally { |
|
144 |
try { |
|
145 |
httpClient.close(); |
|
146 |
} catch (IOException e) { |
|
147 |
e.printStackTrace(); |
|
148 |
} |
|
149 |
} |
|
150 |
} |
|
151 |
|
|
152 |
public void addHeader(HttpPost httpPost) { |
|
153 |
|
|
154 |
TxTransactionLocal txTransactionLocal = TxTransactionLocal.current(); |
|
155 |
String groupId = txTransactionLocal == null ? null : txTransactionLocal.getGroupId(); |
|
156 |
|
|
157 |
log.info("LCN-SpringCloud TxGroup info -> groupId:"+groupId); |
|
158 |
|
|
159 |
if(txTransactionLocal!=null) { |
|
160 |
httpPost.setHeader("tx-group", groupId); |
|
161 |
} |
|
162 |
if(null != cookie) { |
|
163 |
httpPost.setHeader(COOKIE_KEY, mapToStrByCookie(cookie)); |
|
164 |
} |
|
165 |
} |
|
166 |
|
|
167 |
public static interface ResultFormat<T>{ |
|
168 |
|
|
169 |
T format(String json); |
|
170 |
|
|
171 |
} |
|
172 |
|
|
173 |
// HttpAgent |
|
174 |
public HttpResponse httpAgent() throws Exception { |
|
175 |
// 创建HttpClientBuilder |
|
176 |
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); |
|
177 |
// HttpClient |
|
178 |
CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); |
|
179 |
// 依次是目标请求地址,端口号,协议类型 |
|
180 |
HttpHost target = new HttpHost(url); |
|
181 |
// 依次是代理地址,代理端口号,协议类型 |
|
182 |
HttpHost proxy = new HttpHost("10.4.32.59", 80, "http"); |
|
183 |
RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); |
|
184 |
|
|
185 |
// 请求地址 |
|
186 |
HttpPost httpPost = new HttpPost(url); |
|
187 |
setHttpEntity(httpPost); |
|
188 |
if(null != cookie) |
|
189 |
httpPost.setHeader(COOKIE_KEY, mapToStrByCookie(cookie)); |
|
190 |
if(null != requestConfig) |
|
191 |
httpPost.setConfig(requestConfig); |
|
192 |
|
|
193 |
httpPost.setConfig(config); |
|
194 |
|
|
195 |
//新加 |
|
196 |
setHttpEntity(httpPost); |
|
197 |
log.debug("httpPost->"+httpPost); |
|
198 |
log.debug("bodyInfos->"+bodyInfos); |
|
199 |
|
|
200 |
HttpResponse response = closeableHttpClient.execute( |
|
201 |
target, httpPost); |
|
202 |
// getEntity() |
|
203 |
log.debug("调试close前:"+response); |
|
204 |
closeableHttpClient.close(); |
|
205 |
log.debug("调试close后:"+response); |
|
206 |
return response; |
|
207 |
|
|
208 |
} |
|
209 |
|
|
210 |
/* |
|
211 |
* 获得httpEntity |
|
212 |
*/ |
|
213 |
private void setHttpEntity(HttpPost httpPost){ |
|
214 |
if(bodyInfos == null) return; |
|
215 |
httpPost.setEntity(bodyInfos); |
|
216 |
} |
|
217 |
|
|
218 |
@SuppressWarnings({ "unchecked", "hiding" }) |
|
219 |
private <T> T httpEntityToStr(HttpEntity httpEntity) throws InstantiationException, IllegalAccessException{ |
|
220 |
log.debug("httpEntity.toString()"+httpEntity.toString()); |
|
221 |
try { |
|
222 |
String json = EntityUtils.toString(httpEntity, BaseConst.PROJECT_CHARSET); |
|
223 |
return (T) JSONTool.toObj(json, this); |
|
224 |
} catch (ParseException | IOException e) { |
|
225 |
log.error(e.getMessage(), e); |
|
226 |
return null; |
|
227 |
} |
|
228 |
} |
|
229 |
private void setParam(){ |
|
230 |
if(params == null || params.isEmpty()) |
|
231 |
return ; |
|
232 |
StringBuilder paramStr = new StringBuilder(); |
|
233 |
boolean isOne = true; |
|
234 |
for (Map.Entry<String, ? extends Object> entrys : this.params.entrySet()) { |
|
235 |
Object val = entrys.getValue(); |
|
236 |
if(val != null){ |
|
237 |
if(isOne){ |
|
238 |
paramStr.append('?'); |
|
239 |
isOne = false; |
|
240 |
}else{ |
|
241 |
paramStr.append('&'); |
|
242 |
} |
|
243 |
if(val instanceof CharSequence || val instanceof Number){ |
|
244 |
paramStr.append(entrys.getKey()).append('=').append(URLTool.encoder(val.toString())); |
|
245 |
}else { |
|
246 |
paramStr.append(entrys.getKey()).append('=').append(URLTool.encoder(JSONTool.toJson(val))); |
|
247 |
|
|
248 |
} |
|
249 |
} |
|
250 |
} |
|
251 |
if(paramStr.length() != 0){ |
|
252 |
this.url = paramStr.insert(0, url).toString(); |
|
253 |
} |
|
254 |
|
|
255 |
} |
|
256 |
|
|
257 |
private String mapToStrByCookie(Map<String, ? extends Object> cookies){ |
|
258 |
StringBuilder str = new StringBuilder(); |
|
259 |
for (Map.Entry<String, ? extends Object> eachCookie : cookies.entrySet()) { |
|
260 |
if(str.length() == 0){ |
|
261 |
str.append(eachCookie.getKey()).append('=').append( |
|
262 |
eachCookie.getValue() instanceof String |
|
263 |
? |
|
264 |
eachCookie.getValue() |
|
265 |
: |
|
266 |
JSONTool.toJson(eachCookie.getValue())); |
|
267 |
}else{ |
|
268 |
str.append(';').append(eachCookie.getKey()).append('=').append( |
|
269 |
eachCookie.getValue() instanceof String |
|
270 |
? |
|
271 |
eachCookie.getValue() |
|
272 |
: |
|
273 |
JSONTool.toJson(eachCookie.getValue())); |
|
274 |
} |
|
275 |
} |
|
276 |
return str.toString(); |
|
277 |
} |
|
278 |
|
|
279 |
public void setCookie(Map<String, ? extends Object> cookie) { |
|
280 |
|
|
281 |
this.cookie = cookie; |
|
282 |
} |
|
283 |
|
|
284 |
public Object getBodyInfos() { |
|
285 |
return bodyInfos; |
|
286 |
} |
|
287 |
|
|
288 |
public void setBodyInfos(Object param) { |
|
289 |
if(param instanceof HttpEntity){ |
|
290 |
this.bodyInfos = (HttpEntity) param; |
|
291 |
}else{ |
|
292 |
String p ; |
|
293 |
log.debug("参数:"+ (p = JSONTool.toJson(param))); |
|
294 |
StringEntity stringEntity = new StringEntity(p, BaseConst.PROJECT_CHARSET); |
|
295 |
stringEntity.setContentType(APPLICATION_JSON); |
|
296 |
this.bodyInfos = stringEntity; |
|
297 |
} |
|
298 |
} |
|
299 |
|
|
300 |
public static HttpEntity getUrlEntity(Map<String, Object> map){ |
|
301 |
List<BasicNameValuePair> params=new ArrayList<>(); |
|
302 |
for (Map.Entry<String, Object> entry : map.entrySet()) { |
|
303 |
Object val = entry.getValue(); |
|
304 |
if(val != null){ |
|
305 |
if(val instanceof Number || val instanceof CharSequence){ |
|
306 |
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); |
|
307 |
}else{ |
|
308 |
params.add(new BasicNameValuePair(entry.getKey(), JSONTool.toJson(entry.getValue()))); |
|
309 |
} |
|
310 |
} |
|
311 |
} |
|
312 |
try { |
|
313 |
return new UrlEncodedFormEntity(params, BaseConst.PROJECT_CHARSET); |
|
314 |
} catch (UnsupportedEncodingException e) { |
|
315 |
log.error(e.getMessage(), e); |
|
316 |
return null; |
|
317 |
} |
|
318 |
} |
|
319 |
|
|
320 |
public Map<String,Object> getParams() { |
|
321 |
return params; |
|
322 |
} |
|
323 |
|
|
324 |
public void setParams(Map<String,Object> params) { |
|
325 |
this.params = params; |
|
326 |
setParam(); |
|
327 |
} |
|
328 |
|
|
329 |
public RequestConfig getRequestConfig() { |
|
330 |
return requestConfig; |
|
331 |
} |
|
332 |
|
|
333 |
public void setRequestConfig(RequestConfig requestConfig) { |
|
334 |
this.requestConfig = requestConfig; |
|
335 |
} |
|
336 |
|
|
337 |
public String getUrl() { |
|
338 |
return url; |
|
339 |
} |
|
340 |
|
|
341 |
public void setUrl(String url) { |
|
342 |
this.url = url; |
|
343 |
} |
|
344 |
|
|
345 |
} |