httpclient-4.5解決https訪問跳過證書校驗

package com.sinocc.util;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;


/***
 * 利用HttpClient進行post請求的工具類
 * 
 * @author gxy 2018年11月8日 my-work success when you begin
 */
public class HttpClientUtil45 {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil45.class);
	static CloseableHttpClient httpClient;
	static CloseableHttpResponse httpResponse;

	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();

	}
	
	/**
	 * 發送https get請求
	 * @param params 這個參數將會自動追加到url後面
	 * @param url
	 * @return
	 */
	public static String sendByHttpsGet(Map<String,String>params,String url) {
		
		if(params ==null || params.size()==0) {
			return "參數不合法";
		}
		Assert.hasText(url, "參數不合法");
		
		StringBuffer param = new StringBuffer("?");
		
		Set<String> keys = params.keySet();
		
		int i = 0 ;
		int max = keys.size();
		
		for (String key : keys) {
			param.append(key+"="+params.get(key));
			if(i<max-1) {
				param.append("&");
			}
			i++;
			
		}
		
		url += param.toString();
		
		logger.info("創建請求httpGet-URL={}", url);
		
		try {
			
			HttpGet httpGet = new HttpGet(url);
			httpClient = HttpClientUtil45.createSSLClientDefault();
			httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
				return jsObject;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}finally {
			try {
				httpResponse.close();
				httpClient.close();
				logger.info("請求流關閉完成");
			} catch (IOException e) {
				logger.info("請求流關閉出錯");
				e.printStackTrace();
			}
		}
		
		return null;
	}

	/**
	 * 發送https post請求
	 * 
	 * @param jsonPara
	 * @throws Exception
	 */
	public static String sendByHttpsPost(Map<String, Object> params, String url) {
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> listNVP = new ArrayList<NameValuePair>();
			if (params != null) {
				for (String key : params.keySet()) {
					listNVP.add(new BasicNameValuePair(key, params.get(key).toString()));
				}
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listNVP, "UTF-8");
			logger.info("創建請求httpPost-URL={},params={}", url, listNVP);
			httpPost.setEntity(entity);
			httpClient = HttpClientUtil45.createSSLClientDefault();
			httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
				return jsObject;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				httpResponse.close();
				httpClient.close();
				logger.info("請求流關閉完成");
			} catch (IOException e) {
				logger.info("請求流關閉出錯");
				e.printStackTrace();
			}
		}
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章