//maven依赖
org.apache.httpcomponents
httpclient
4.5.6
importjava.io.IOException;importjava.net.URI;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;//import org.apache.commons.collections.MapUtils;
importorg.apache.http.Consts;importorg.apache.http.HeaderIterator;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;importorg.apache.http.ParseException;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.config.Registry;importorg.apache.http.config.RegistryBuilder;importorg.apache.http.conn.socket.ConnectionSocketFactory;importorg.apache.http.conn.socket.PlainConnectionSocketFactory;importorg.apache.http.conn.ssl.NoopHostnameVerifier;importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;importorg.apache.http.conn.ssl.TrustStrategy;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.ssl.SSLContextBuilder;importorg.apache.http.util.EntityUtils;/***
* @ClassName: HttpsUtils
* @Description: TODO(https post忽略证书请求)*/
public classHttpClientUtils {private static final String HTTP = "http";private static final String HTTPS = "https";private static SSLConnectionSocketFactory sslsf = null;private static PoolingHttpClientConnectionManager cm = null;private static SSLContextBuilder builder = null;static{try{
builder= newSSLContextBuilder();//全部信任 不做身份鉴定
builder.loadTrustMaterial(null, newTrustStrategy() {
@Overridepublic boolean isTrusted(X509Certificate[] x509Certificates, String s) throwsCertificateException {return true;
}
});
sslsf= newSSLConnectionSocketFactory(builder.build(),new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry registry = RegistryBuilder.create()
.register(HTTP,newPlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm= newPoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);//max connection
} catch(Exception e) {
e.printStackTrace();
}
}//public static String post(String url, Map header, Map param, StringEntity entity)//throws Exception {//String result = "";//CloseableHttpClient httpClient = null;//try {//httpClient = getHttpClient();// //HttpGet httpPost = new HttpGet(url);//get请求//HttpPost httpPost = new HttpPost(url);//Post请求// //设置头信息//if (MapUtils.isNotEmpty(header)) {//for (Map.Entry entry : header.entrySet()) {//httpPost.addHeader(entry.getKey(), entry.getValue());//}//}// //设置请求参数//if (MapUtils.isNotEmpty(param)) {//List formparams = new ArrayList();//for (Map.Entry entry : param.entrySet()) {// //给参数赋值//formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));//}//UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);//httpPost.setEntity(urlEncodedFormEntity);//}// //设置实体 优先级高//if (entity != null) {//httpPost.addHeader("Content-Type", "text/xml");//httpPost.setEntity(entity);//}//HttpResponse httpResponse = httpClient.execute(httpPost);//int statusCode = httpResponse.getStatusLine().getStatusCode();//System.out.println("状态码:" + statusCode);//if (statusCode == HttpStatus.SC_OK) {//HttpEntity resEntity = httpResponse.getEntity();//result = EntityUtils.toString(resEntity);//} else {//readHttpResponse(httpResponse);//}//} catch (Exception e) {//throw e;//} finally {//if (httpClient != null) {//httpClient.close();//}//}//return result;//}
public staticString postXML(String url,String xml){
CloseableHttpClient client= null;
CloseableHttpResponse resp= null;try{
HttpPost httpPost= newHttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
client=HttpClients.createDefault();
StringEntity entityParams= new StringEntity(xml,"utf-8");
httpPost.setEntity(entityParams);
client=HttpClients.createDefault();
resp=client.execute(httpPost);
String resultMsg= EntityUtils.toString(resp.getEntity(),"utf-8");returnresultMsg;
}catch(Exception e){
e.printStackTrace();
}finally{try{if(client!=null){
client.close();
}if(resp != null){
resp.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}return null;
}public static CloseableHttpClient getHttpClient() throwsException {
CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).build();returnhttpClient;
}public static String readHttpResponse(HttpResponse httpResponse) throwsParseException, IOException {
StringBuilder builder= newStringBuilder();//获取响应消息实体
HttpEntity entity =httpResponse.getEntity();//响应状态
builder.append("status:" +httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator=httpResponse.headerIterator();while(iterator.hasNext()) {
builder.append("\t" +iterator.next());
}//判断响应实体是否为空
if (entity != null) {
String responseString=EntityUtils.toString(entity);
builder.append("response length:" +responseString.length());
builder.append("response content:" + responseString.replace("\r\n", ""));
}returnbuilder.toString();
}/*** get发送数据
*@paramurl
*@paramparam
*@return
*/
public static String doGet(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpclient =HttpClients.createDefault();
String resultString= "";
CloseableHttpResponse response= null;try{//创建uri
URIBuilder builder = newURIBuilder(url);if (param != null) {for(String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri=builder.build();//创建http GET请求
HttpGet httpGet = newHttpGet(uri);//执行请求
response =httpclient.execute(httpGet);//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString= EntityUtils.toString(response.getEntity(), "UTF-8");
}
}catch(Exception e) {
e.printStackTrace();
}finally{try{if (response != null) {
response.close();
}
httpclient.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}/*** get发送数据
*@paramurl
*@return
*/
public staticString doGet(String url) {return doGet(url, null);
}/*** post发送数据
*@paramurl
*@paramparam
*@return
*/
public static String doPost(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建参数列表
if (param != null) {
List paramList = new ArrayList<>();for(String key : param.keySet()) {
paramList.add(newBasicNameValuePair(key, param.get(key)));
}//模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnresultString;
}/*** post发送数据
*@paramurl
*@return
*/
public staticString doPost(String url) {return doPost(url, null);
}/*** post发送json形式的数据
*@paramurl
*@paramjson
*@return
*/
public staticString doPostJson(String url, String json) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建请求内容
StringEntity entity = newStringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnresultString;
}
}