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;
|
}
|
|
}
|