package com.changhong.epc.form.tool;
|
|
import com.changhong.epc.constter.base.BaseConst;
|
import com.iemsoft.framework.cloud.core.tools.JSONTool;
|
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.LogFactory;
|
import org.apache.http.HttpEntity;
|
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.HttpClients;
|
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.util.EntityUtils;
|
|
import java.io.IOException;
|
import java.io.UnsupportedEncodingException;
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.concurrent.TimeoutException;
|
|
|
/**
|
* @ClassName: HttpClientTool
|
* @Description: TODO[后台发送请求工具类]
|
* @author [九鼎联合科技]
|
* @date 2017年2月27日 下午5:19:57
|
*/
|
public class HttpClientTool<T> {
|
|
static Log log = LogFactory.getLog(HttpClientTool.class);
|
|
public static final String COOKIE_KEY = "Cookie";
|
|
public static final String APPLICATION_JSON = "application/json;charset=utf-8";
|
/**
|
* 访问url
|
*/
|
private String url;
|
|
private HttpClient httpClient;
|
|
private Map<String, Object> params;
|
|
private HttpEntity bodyInfos;
|
|
private Map<String, ? extends Object> cookie;
|
|
private RequestConfig requestConfig;
|
|
private Class<T> resultClazz;
|
|
private boolean resultArray;
|
|
public HttpClientTool(String url) {
|
this.url = url;
|
this.httpClient = HttpClients.createDefault();
|
}
|
|
public HttpClientTool() {
|
|
}
|
|
|
public Class<T> getResultClazz() {
|
return resultClazz;
|
}
|
|
public HttpClientTool<T> setResultClazz(Class<T> resultClazz) {
|
this.resultClazz = resultClazz;
|
return this;
|
}
|
|
public boolean isResultArray() {
|
return resultArray;
|
}
|
|
public HttpClientTool<T> setResultArray(boolean resultArray) {
|
this.resultArray = resultArray;
|
return this;
|
}
|
|
/**
|
* 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);
|
}
|
|
if(null != cookie){
|
httpGet.setHeader(COOKIE_KEY, mapToStrByCookie(cookie));
|
}
|
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() throws TimeoutException{
|
log.debug(String.format("开始发送post请求:%s", url));
|
|
HttpPost httpPost = new HttpPost(url);
|
setHttpEntity(httpPost);
|
// RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50000)
|
// .setConnectionRequestTimeout(10000).setSocketTimeout(50000).build();
|
if(null != cookie){
|
httpPost.setHeader(COOKIE_KEY, mapToStrByCookie(cookie));
|
}
|
if(null != requestConfig){
|
httpPost.setConfig(requestConfig);
|
}
|
try {
|
long begin = System.currentTimeMillis();
|
HttpResponse response = this.httpClient.execute(httpPost);
|
log.debug("请求时间:"+ (System.currentTimeMillis() - begin));
|
T obj ;
|
obj = httpEntityToStr(response.getEntity());
|
log.debug(String.format("响应返回值为:%s", JSONTool.toJson(obj)));
|
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());
|
}
|
}
|
|
/*
|
* 获得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);
|
if(resultArray){
|
return (T) JSONTool.toList(json, resultClazz);
|
}else{
|
return (T) JSONTool.toObj(json, resultClazz);
|
}
|
} catch (ParseException | IOException e) {
|
log.error(e.getMessage(), e);
|
return (T) resultClazz.newInstance();
|
}
|
}
|
|
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{
|
StringEntity stringEntity = new StringEntity(JSONTool.toJson(param), 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 HttpClient getHttpClient() {
|
return httpClient;
|
}
|
|
public void setHttpClient(HttpClient httpClient) {
|
this.httpClient = httpClient;
|
}
|
|
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;
|
}
|
|
}
|