package test;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
import com.alibaba.druid.util.HttpClientUtils;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.entity.mime.content.FileBody;
import app.base.ServiceException;
import javax.net.ssl.SSLContext;
/**
* httpclient请求工具类
* @author
*
*/
public class HttpClientUtil {
protected static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 20000;
private static String log_req_url = "请求地址-->";
private static String log_req_parm = "请求参数-->";
static{
// 设置连接池
// connMgr = new PoolingHttpClientConnectionManager();
// connMgr.setMaxTotal(100);
// connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
/**
* post请求
* @param parmMap
* @param url
* @return
* @throws ServiceException
*/
public static String sendPost(Map<String, String> parmMap, String url) throws ServiceException {
String result = null;
CloseableHttpClient httpclient = null;
HttpPost httppost = null;
HttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : parmMap.entrySet()) {
if (entry.getValue() == null || entry.getValue().equals("")) continue;
BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), (String) entry.getValue());
params.add(pair);
}
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));//解决中文乱码问题
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
httppost.abort();
} catch (Exception e) {
log.error(log_req_url + url);
log.error(log_req_parm + parmMap);
throw new ServiceException(e);
} finally {
if(null != httpclient)
{
try {
httpclient.close();
} catch (IOException e) {
throw new ServiceException(e);
}
}
}
return result;
}
/**
* post请求 JSON格式
* @param parmMap
* @param url
* @return
* @throws ServiceException
*/
public static String sendPostJson(Map<String, String> parmMap,String url) throws ServiceException {
String result = null;
CloseableHttpClient httpclient = null;
HttpPost httppost = null;
try {
httpclient = HttpClients.createDefault();
httppost = new HttpPost(url);
JSONObject jsonParam = new JSONObject();
for (Map.Entry<String, String> entry : parmMap.entrySet()) {
if(entry.getValue() == null||entry.getValue().equals("")) continue;
jsonParam.put(entry.getKey(), entry.getValue());
}
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
httppost.abort();
} catch (Exception e) {
log.error(log_req_url + url);
log.error(log_req_parm + parmMap);
throw new ServiceException(e);
}finally {
if(null != httpclient)
{
try {
httpclient.close();
} catch (IOException e) {
throw new ServiceException(e);
}
}
}
return result;
}
/**
* post请求 JSON格式
* @param jsonParm
* @param url
* @return
* @throws ServiceException
*/
public static String sendPostJson(String jsonParm,String url) throws ServiceException {
String result = null;
CloseableHttpClient httpclient = null;
HttpPost httppost = null;
try {
httpclient = HttpClients.createDefault();
httppost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonParm,"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
httppost.abort();
} catch (Exception e) {
log.error(log_req_url + url);
log.error(log_req_parm + jsonParm);
throw new ServiceException(e);
}finally {
if(null != httpclient)
{
try {
httpclient.close();
} catch (IOException e) {
throw new ServiceException(e);
}
}
}
return result;
}
/**
* 发送https请求
* 返回结果全部原样输出
* @param parmMap
* @param url
* @return
*/
public static String doPostSSLJsonALLReturn(Map<String, String> parmMap,String url) {
CloseableHttpClient httpClient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String httpStr = null;
try {
StringEntity stringEntity = new StringEntity(new Gson().toJson(parmMap),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// if (statusCode != HttpStatus.SC_OK) {
// return null;
// }
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送https请求
* @param parmMap
* @param url
* @return
*/
public static String doPostSSLJson(Map<String, String> parmMap,String url) {
CloseableHttpClient httpClient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String httpStr = null;
try {
JSONObject jsonParam = new JSONObject();
for (Map.Entry<String, String> entry : parmMap.entrySet()) {
if(entry.getValue() == null) continue;
jsonParam.put(entry.getKey(), entry.getValue());
}
StringEntity stringEntity = new StringEntity(jsonParam.toString(),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 发送https请求
* @param parmMap
* @param url
* @return
*/
public static String doPostSSL(Map<String, String> parmMap,String url) {
CloseableHttpClient httpClient = createSSLClientDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String httpStr = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : parmMap.entrySet()) {
if (entry.getValue() == null || entry.getValue().equals("")) continue;
BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), (String) entry.getValue());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));//解决中文乱码问题
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 下载文件
*
* @param url
* @param filePath
*/
private void httpDownloadFile(String url, String filePath, Map<String, String> headMap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
HttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1.getStatusLine());
HttpEntity httpEntity = response1.getEntity();
InputStream is = httpEntity.getContent();
// 根据InputStream 下载文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public static String uploadFileImpl(String serverUrl, String localFilePath,
String serverFieldName, Map<String, String> params)
throws Exception {
String respStr ;
CloseableHttpClient httpclient = createSSLClientDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
FileBody binFileBody = new FileBody(new File(localFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
// 设置上传的其他参数
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
private static String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
/**
* 设置上传文件时所附带的其他参数
*
* @param multipartEntityBuilder
* @param params
*/
private static void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map<String, String> params) {
if (params != null && params.size() > 0) {
Set<String> keys = params.keySet();
for (String key : keys) {
multipartEntityBuilder
.addPart(key, new StringBody(params.get(key),
ContentType.TEXT_PLAIN));
}
}
}
/**
* 设置http的HEAD
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
if (headMap != null && headMap.size() > 0) {
Set<String> keySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}
/**
* 使用demo
* @param args
*/
/*public static void main(String[] args) {
// GET 同步方法
httpDownloadFile( "http://wthrcdn.etouch.cn/weather_mini?city=北京", filePath, null, null);
// 上传文件 POST 同步方法
try {
Map<String,String> uploadParams = new LinkedHashMap<String, String>();
uploadParams.put("userImageContentType", "image");
uploadParams.put("userImageFileName", "testaa.png");
this.uploadFileImpl(
"http://192.xxx.xxx.xxx:8080/xxxx/xxxx", "android_bug_1.png",
"userImage", uploadParams);
} catch (Exception e) {
e.printStackTrace();
}
}*/
}
复制就可以用HttpClientUtil,简单方便
于 2020-12-21 14:36:12 首次发布