package com.cetron.common.utils.Http;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* HttpClient 4
* */
public class HttpClient {
//日记记录(日志记录工具类在此不提供)
static final Logger log= Logger.getLogger(HttpClient.class);
private static CloseableHttpClient httpClient = null;
private static CloseableHttpResponse response = null;
private static RequestConfigrequestConfig = null;
static {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
requestConfig =RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
.setSocketTimeout(60000)// 设置读取数据连接超时时间
.build();
}
public static String doGet(Stringurl) {
CloseableHttpResponse response = null;
String result ="";
try {
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntityentity = response.getEntity();
result =EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
log.debug( "服务器连接出现异常",e );
} catch (IOException e) {
log.debug( "服务器连接出现异常",e );
} catch (Exception e) {
log.debug( "服务器连接出现异常",e );
}finally {
if (null !=response) {
try{
response.close();
} catch (IOException e) {
log.debug("关闭服务器连接出现异常",e );
}
}
if (null !=httpClient) {
try{
httpClient.close();
} catch (IOException e) {
log.debug("关闭服务器连接出现异常",e );
}
}
}
return result;
}
public static String doPost(Stringurl, Object obj) {
String result = "";
HttpPosthttpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
try {
HttpEntity entityParam = new StringEntity(new Gson().toJson( obj ),"UTF-8");
httpPost.setEntity(entityParam);
response = httpClient.execute(httpPost);
HttpEntityentity = response.getEntity();
result =EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
log.debug( "服务器连接出现异常",e );
} catch (IOException e) {
log.debug("服务器连接出现异常",e );
} catch (Exception e) {
log.debug( "服务器连接出现异常",e );
} finally {
// 关闭资源
if (null!= response) {
try{
response.close();
} catch (IOException e) {
log.debug("中转服务器连接出现异常",e );
}
}
if (null !=httpClient) {
try{
httpClient.close();
} catch (IOException e) {
log.debug("中转服务器连接出现异常",e );
}
}
}
return result;
}
}
此代码仅供连接第三方服务器使用,发送请求到服务器,请求在第三方服务器处理,可以在分布式架构中当做通讯桥梁.仅供自己学习记录使用