public class HttpClientUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
public static String doGet(String url, Map<String, String> param) {
return doGet(url, param, "");
}
public static String doGet(String url, String body) {
return doGet(url, null, body);
}
public static String doGet(String url) {
return doGet(url, null,"");
}
@SuppressWarnings("deprecation")
public static String doGet(String url, Map<String, String> param, String body) {
CloseableHttpClient httpclient = null;
String resultString = "";
CloseableHttpResponse response = null;
try {
if(url.startsWith("https")){
httpclient = getIgnoeSSLClient();
} else {
httpclient = HttpClients.createDefault();
}
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
} else if (StringUtils.isNotEmpty(body)) {
builder.setQuery(body);
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do get error.", e);
return resultString;
} finally {
try {
if (response != null) {
response.close();
}
if(httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
logger.error("do get error.", e);
}
}
return resultString;
}
public static String doPost(String url, Map<String, String> param) {
return doPost(url, param, "");
}
public static String doPost(String url, String body) {
return doPost(url, null, body);
}
public static String doPost(String url, Map<String, String> param, String body) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Httpclient对象
if(url.startsWith("https")){
httpClient = getIgnoeSSLClient();
} else {
httpClient = HttpClients.createDefault();
}
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
} else if (StringUtils.isNotEmpty(body)) {
StringEntity entity = null;
try {
entity = new StringEntity(body, "UTF-8");
} catch (UnsupportedCharsetException ex) {
ex.printStackTrace();
}
httpPost.setEntity(entity);
// post.setRequestBody(body);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do post error.", e);
return resultString;
} finally {
try {
if(response != null) {
response.close();
}
if(httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null,"");
}
public static String doPost(String url,Map<String, String> head, Map<String, String> bodyParam) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Httpclient对象
if(url.startsWith("https")){
httpClient = getIgnoeSSLClient();
} else {
httpClient = HttpClients.createDefault();
}
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 创建参数列表
if (head != null) {
for (String key : head.keySet()) {
httpPost.setHeader(key, head.get(key));
}
}
if (bodyParam != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : bodyParam.keySet()) {
paramList.add(new BasicNameValuePair(key, bodyParam.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do post error.", e);
return resultString;
} finally {
try {
if(response != null) {
response.close();
}
if(httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostJson(String url, String json) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Httpclient对象
if(url.startsWith("https")){
httpClient = getIgnoeSSLClient();
} else {
httpClient = HttpClients.createDefault();
}
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do post error.", e);
return resultString;
} finally {
try {
if (response != null) {
response.close();
}
if(httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* http发送文件
* @param url
* @param localFilePath
* @return
*/
public static String doPostFile(String url, String localFilePath) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Httpclient对象
if(url.startsWith("https")){
httpClient = getIgnoeSSLClient();
} else {
httpClient = HttpClients.createDefault();
}
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
// 把文件转换成流对象FileBody
File localFile = new File(localFilePath);
FileBody fileBody = new FileBody(localFile);
// 以浏览器兼容模式运行,防止文件名乱码。
HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).
addPart("uploadFile", fileBody).setCharset(CharsetUtils.get("UTF-8")).build();
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do post error.", e);
return resultString;
} finally {
try {
if (response != null) {
response.close();
}
if(httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPut(String url, String json) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Httpclient对象
if(url.startsWith("https")){
httpClient = getIgnoeSSLClient();
} else {
httpClient = HttpClients.createDefault();
}
HttpPut httpPut = new HttpPut(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
// //设置请求超时时间
// RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
// httpPut.setConfig(requestConfig);
// 执行http请求
response = httpClient.execute(httpPut);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
if(url.startsWith("https")){
EntityUtils.consume(response.getEntity());
}
} catch (Exception e) {
logger.error("do put error.", e);
return resultString;
} finally {
try {
if (response != null) {
response.close();
}
if(httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static CloseableHttpClient getIgnoeSSLClient() throws Exception {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
return client;
}
}