目的與初衷
最近在工作中需要在后臺調(diào)用第三方接口(微信雀彼,支付瓷蛙,華為點(diǎn)擊回?fù)埽ㄒ贿_(dá)物流快遞接口)伟件,最近在學(xué)習(xí)Kotlin硼啤,嘗試使用Kotlin和HttpClient,自己封裝了一個HttpClient工具類斧账,封裝常用實(shí)現(xiàn)get谴返,post工具方法類
1 什么是HttpClient
HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了咧织,越來越多的 Java 應(yīng)用程序需要直接通過 HTTP 協(xié)議來訪問網(wǎng)絡(luò)資源嗓袱。雖然在 JDK 的 java net包中已經(jīng)提供了訪問 HTTP 協(xié)議的基本功能,但是對于大部分應(yīng)用程序來說习绢,JDK 庫本身提供的功能還不夠豐富和靈活渠抹。HttpClient 是Apache HttpComponents 下的子項(xiàng)目,用來提供高效的闪萄、最新的梧却、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議败去。
2 功能介紹
- 支持自動轉(zhuǎn)向
- 支持 HTTPS 協(xié)議
- 支持代理服務(wù)器等
3. 版本比較
注意本篇博客主要是基于 HttpClient4.5.5 版本的來講解的放航,也是現(xiàn)在最新的版本,之所以要提供版本說明的是因?yàn)?HttpClient 3 版本和 HttpClient 4 版本差別還是很多大的圆裕,基本HttpClient里面的接口都變了广鳍,你把 HttpClient 3 版本的代碼拿到 HttpClient 4 上面都運(yùn)行不起來缺菌,會報(bào)錯的。所以一定要注意 HtppClient 的版本問題搜锰。
4. HttpClient不能做的事情
HttpClient 不是瀏覽器伴郁,它是一個客戶端 HTTP 協(xié)議傳輸類庫。HttpClient 被用來發(fā)送和接受 HTTP 消息蛋叼。HttpClient 不會處理 HTTP 消息的內(nèi)容焊傅,不會進(jìn)行 javascript 解析武福,不會關(guān)心 content type趋观,如果沒有明確設(shè)置,HttpClient 也不會對請求進(jìn)行格式化巷查、重定向 url歌馍,或者其他任何和 HTTP 消息傳輸相關(guān)的功能握巢。
5. HttpClient使用流程
使用HttpClient發(fā)送請求、接收響應(yīng)很簡單松却,一般需要如下幾步即可暴浦。
- 創(chuàng)建HttpClient對象。
- 創(chuàng)建請求方法的實(shí)例晓锻,并指定請求URL歌焦。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象砚哆;如果需要發(fā)送POST請求独撇,創(chuàng)建HttpPost對象。
- 如果需要發(fā)送請求參數(shù)躁锁,可調(diào)用HttpGetsetParams方法來添加請求參數(shù)纷铣;對于HttpPost對象而言,可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)战转。
- 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求搜立,該方法返回一個HttpResponse對象。
- 調(diào)用HttpResponse的getAllHeaders()匣吊、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭儒拂;調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容色鸳。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。
- 釋放連接见转。無論執(zhí)行方法是否成功命雀,都必須釋放連接
6、 HttpClient與Java結(jié)合使用
/**
* @Description httpclient客戶端請求處理的通用類
* @ClassName HttpClientUtls
* @Date 2017年6月6日 上午11:41:36
* @Copyright (c) All Rights Reserved, 2017.
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private final static int CONNECT_TIMEOUT = 7000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;
private static PoolingHttpClientConnectionManager connMgr;
private static String LINE = System.getProperty("line.separator");//換行相當(dāng)于\n
static {
// 設(shè)置連接池
connMgr = new PoolingHttpClientConnectionManager();
// 設(shè)置連接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 設(shè)置連接超時(shí)
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 設(shè)置讀取超時(shí)
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 設(shè)置從連接池獲取連接實(shí)例的超時(shí)
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交請求之前 測試連接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
/**
* @Description get請求鏈接
* @Date 2017年6月6日 上午11:36:09
* @param rURL
* @return 參數(shù)
* @return String 返回類型
* @throws
*/
public static String get(String rURL) {
String result = "";
try {
URL url = new URL(rURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(60000);//將讀超時(shí)設(shè)置為指定的超時(shí)斩箫,以毫秒為單位吏砂。用一個非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間撵儿。如果在數(shù)據(jù)可讀取之前超時(shí)期滿,則會引發(fā)一個 java.net.SocketTimeoutException狐血。
con.setDoInput(true);//指示應(yīng)用程序要從 URL 連接讀取數(shù)據(jù)淀歇。
con.setRequestMethod("GET");//設(shè)置請求方式
if(con.getResponseCode() == 200){//當(dāng)請求成功時(shí),接收數(shù)據(jù)(狀態(tài)碼“200”為成功連接的意思“ok”)
InputStream is = con.getInputStream();
result = formatIsToString(is);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
/**
*
* @Description POST請求
* @Date 2017年6月6日 上午11:36:28
* @param postUrl
* @param params
* @return 參數(shù)
* @return String 返回類型
* @throws
*/
public static String post(String postUrl, Map<String, Object> params){
StringBuffer sb = new StringBuffer();
String line;
try {
URL url = new URL(postUrl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpUrlConn = (HttpURLConnection)urlConn;
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(httpUrlConn.getOutputStream());
String content = getConcatParams(params);
wr.write(content);
wr.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(),"utf-8"));
while((line = in.readLine()) != null){
sb.append(line);
}
wr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
*
* @Description 獲取參數(shù)內(nèi)容
* @Date 2017年6月6日 上午11:36:50
* @throws UnsupportedEncodingException 參數(shù)
* @return String 返回類型
* @throws
*/
public static String getConcatParams(Map<String, Object> params) throws UnsupportedEncodingException {
String content = null;
Set<Entry<String,Object>> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 視圖匈织,其中的元素屬于此類
StringBuilder sb = new StringBuilder();
for(Entry<String,Object> i: set){
//將參數(shù)解析為"name=tom&age=21"的模式
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue().toString(), "utf-8")).append("&");
}
if(sb.length() > 1){
content = sb.substring(0, sb.length()-1);
}
return content;
}
public static String formatIsToString(InputStream is)throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
try {
while( (len=is.read(buf)) != -1){
baos.write(buf, 0, len);
}
baos.flush();
baos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(baos.toByteArray(),"utf-8");
}
/**
* @Description 拼接請求參數(shù)
* @Date 2017年5月24日 上午10:39:28
* @param @return 參數(shù)
* @return String 返回結(jié)果如: userName=1111&passWord=222
* @throws
*/
private static String getContent(Map<String, Object> params, String encoding) throws UnsupportedEncodingException {
String content = null;
Set<Entry<String,Object>> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 視圖浪默,其中的元素屬于此類
StringBuilder sb = new StringBuilder();
for(Entry<String,Object> i: set){
//將參數(shù)解析為"name=tom&age=21"的模式
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue().toString(), encoding)).append("&");
}
if(sb.length() > 1){
content = sb.substring(0, sb.length()-1);
}
return content;
}
public static String post(String postUrl, Map<String, Object> params, String encoding){
StringBuffer sb = new StringBuffer();
String line;
try {
URL url = new URL(postUrl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpUrlConn = (HttpURLConnection)urlConn;
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(httpUrlConn.getOutputStream());
String content = getContent(params, encoding);
wr.write(content);
wr.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), encoding));
while((line = in.readLine()) != null){
sb.append(line);
}
wr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public static String get(String rURL, String encoding) {
String result = "";
try {
URL url = new URL(rURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(180000);//將讀超時(shí)設(shè)置為指定的超時(shí),以毫秒為單位缀匕。用一個非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間纳决。如果在數(shù)據(jù)可讀取之前超時(shí)期滿,則會引發(fā)一個 java.net.SocketTimeoutException乡小。
con.setDoInput(true);//指示應(yīng)用程序要從 URL 連接讀取數(shù)據(jù)阔加。
con.setRequestMethod("GET");//設(shè)置請求方式
if(con.getResponseCode() == 200){//當(dāng)請求成功時(shí),接收數(shù)據(jù)(狀態(tài)碼“200”為成功連接的意思“ok”)
InputStream is = con.getInputStream();
result = formatIsToString(is, encoding);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
/**
*
* @Description 格式字符串
* @Date 2017年6月6日 上午11:39:23
* @param is
* @param encoding
* @return
* @throws Exception 參數(shù)
* @return String 返回類型
* @throws
*/
public static String formatIsToString(InputStream is, String encoding) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
try {
while( (len=is.read(buf)) != -1){
baos.write(buf, 0, len);
}
baos.flush();
baos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(baos.toByteArray(), encoding);
}
/**
* @Description HttpUrlConnection
* @Author liangjilong
* @Date 2017年5月17日 上午10:53:00
* @param urlStr
* @param data
* @param contentType
* @param requestMethod
* @param 參數(shù)
* @return String 返回類型
* @throws
*/
public static String createHttp(String reqUrl, String reqBodyParams, String contentType,String requestMethod){
BufferedReader reader = null;
HttpURLConnection conn =null;
try {
URL url = new URL(reqUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.connect();
InputStream inputStream = conn.getInputStream();
if(contentType != null){
conn.setRequestProperty("Content-type", contentType);
}
if(reqBodyParams!=null){
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
writer.write(reqBodyParams);
writer.flush();
writer.close();
}
reader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");//\r是回車\n是換行
}
logger.info("請求鏈接為:"+reqUrl+"返回的數(shù)據(jù)為"+sb.toString());
return sb.toString();
} catch (IOException e) {
logger.error("Error connecting to " + reqUrl + ": " + e.getMessage());
} finally {
try {
if (reader != null){
reader.close();
}
if (conn != null){
conn.disconnect();
}
} catch (IOException e) {
logger.error("Error connecting to finally" + reqUrl + ": " + e.getMessage());
}
}
return null;
}
/**
*
* @Description 建立http請求鏈接支持SSL請求
* @Date 2017年6月6日 上午11:11:56
* @param requestUrl
* @param requestMethod
* @param outputStr
* @param headerMap請求頭屬性满钟,可以為空
* @param isSsl 當(dāng)isSSL=true的時(shí)候支持Https處理胜榔,當(dāng)isSSL=false的時(shí)候http請求
* @param sslVersion 支持https的版本參數(shù)
* @return 參數(shù)
* @return String 返回類型
* @throws
*/
public static String createHttps(String requestUrl, String requestMethod,Map<String,Object> headerMap,
boolean isSsl,String sslVersion,String bodyParams) {
HttpsURLConnection conn = null ;
BufferedReader bufferedReader =null;
InputStreamReader inputStreamReader =null;
InputStream inputStream = null;
try {
SSLSocketFactory ssf = null;
if(isSsl){
//這行代碼必須要在創(chuàng)建URL對象之前,因?yàn)橄刃r?yàn)SSL的https請求通過才可以訪問http
ssf = SSLContextSecurity.createIgnoreVerifySSL(sslVersion);
}
// 從上述SSLContext對象中得到SSLSocketFactory對象
URL url = new URL(requestUrl);
conn = (HttpsURLConnection) url.openConnection();
if(isSsl){
conn.setSSLSocketFactory(ssf);
}
conn.setDoOutput(true);//輸出
conn.setDoInput(true);//輸入
conn.setUseCaches(false);//是否支持緩存
/*設(shè)置請求頭屬性和值 */
if(headerMap!=null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
Object value = headerMap.get(key);
//如:conn.addRequestProperty("Authorization","123456");
conn.addRequestProperty(key,String.valueOf(value));
}
}
// 設(shè)置請求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 當(dāng)設(shè)置body請求參數(shù)
if (!ObjectUtil.isEmpty(bodyParams)) {
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(bodyParams.getBytes("UTF-8"));
outStream.close();
outStream.flush();
}
if(conn!=null && conn.getResponseCode()==200){
// 從輸入流讀取返回內(nèi)容
inputStream = conn.getInputStream();
inputStreamReader= new InputStreamReader(inputStream, "UFT-8");
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
buffer.append("\r").append(LINE);
}
return buffer.toString();
}else{
return "FAIL";
}
} catch (ConnectException ce) {
logger.error("連接超時(shí):{}", ce+"\t請求鏈接"+requestUrl);
} catch (Exception e) {
logger.error("https請求異常:{}", e+"\t請求鏈接"+requestUrl);
return "FAIL";//請求系統(tǒng)頻繁
}finally{
// 釋放資源
try {
if(conn!=null){conn.disconnect();}
if(bufferedReader!=null){bufferedReader.close();}
if(inputStreamReader!=null){inputStreamReader.close();}
if(inputStream!=null){
inputStream.close();
inputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 發(fā)送 POST 請求(HTTP)湃番,JSON形式
* @Author liangjilong
* @Date 2017年5月22日 下午3:57:03
* @param @param apiUrl
* @param @param json
* @param @param contentType
* @param @return 參數(shù)
* @return String 返回類型
* @throws
*/
public static String httpClientPost(String reqUrl, Object reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {
String result ="";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqUrl);
/*設(shè)置請求頭屬性和值 */
if(headerMap!=null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
Object value = headerMap.get(key);
//如: httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader(key,String.valueOf(value));
}
}
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
if(reqBodyParams!=null){
logger.info(getCurrentClassName()+".httpClientPost方法返回的參數(shù)為:"+reqBodyParams.toString());
StringEntity stringEntity = new StringEntity(reqBodyParams.toString(),(encoding==null||"".equals(encoding)?"utf-8":encoding));//解決中文亂碼問題
if(encoding!=null && encoding!=""){
stringEntity.setContentEncoding(encoding);
}
if(contentType!=null && contentType!=""){
stringEntity.setContentType(contentType);
}
httpPost.setEntity(stringEntity);
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode()==200) {
//Attempted read from closed stream,因?yàn)镋ntityUtils.toString(HttpEntity)方法被使用了多次苗分。所以每個方法內(nèi)只能使用一次。
//httpStr = EntityUtils.toString(entity, "UTF-8");
String buffer = IoUtils.getInputStream(entity.getContent());
logger.info("HttpUrlPost的entity返回的信息為:"+buffer.toString());
return buffer.toString();//返回
}else{
logger.error("HttpUrlPost的entity對象為空");
return result;
}
} catch (IOException e) {
logger.error("HttpUrlPost出現(xiàn)異常牵辣,異常信息為:"+e.getMessage());
e.printStackTrace();
} finally {
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* @Description 發(fā)送 POST 請求(HTTP)摔癣,JSON形式
* @Author liangjilong
* @throws
*/
public static String httpClientPost(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
return commonHttpClientPost(reqUrl, reqBodyParams, contentType, encoding, headerMap, httpClient);
}
/**
* @Description httpClientGet
* @Date 2017年5月22日 下午3:57:03
* @return String 返回類型
* @throws
*/
public static String httpClientGet(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = commonHttpClientGet(reqUrl, reqBodyParams, encoding,
headerMap, httpClient);
return httpStr;
}
/**
* @Description reqParamStr
* @param reqBodyParams
* @param encoding
* @param reqParamStr
* @return
* @throws IOException
* @throws UnsupportedEncodingException 參數(shù)
* @return String 返回類型
*/
private static String reqParamStr(Map<String, Object> reqBodyParams, String encoding, String reqParamStr) throws IOException,
UnsupportedEncodingException {
if(reqBodyParams!=null && !reqBodyParams.isEmpty()){
//封裝請求參數(shù)
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : reqBodyParams.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
params.add(new BasicNameValuePair(key, val.toString()));
}
reqParamStr = EntityUtils.toString(new UrlEncodedFormEntity(params,encoding));
//httpGet.setURI(new URIBuilder(httpGet.getURI().toString() + "?" + param).build());
}
return reqParamStr;
}
/**
* @Description 創(chuàng)建httpClient
* @Date 2017年8月1日 上午10:26:29
* @return 參數(shù)
* @return CloseableHttpClient 返回類型
*/
public static CloseableHttpClient createHttpClient() {
SSLContext sslcontext = null;
try {
sslcontext = new SSLContextBuilder().loadTrustMaterial(null,
new TrustStrategy()
{ @Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (KeyStoreException e) {
return null;
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
}
/**
* @Description 創(chuàng)建httpsPost
* @Date 2017年8月1日 上午10:29:09
* @param reqUrl
* @param reqBodyParams
* @param contentType
* @param encoding
* @param headerMap
* @return 參數(shù)
* @return String 返回類型
*/
public static String createHttpsPost(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {
CloseableHttpClient httpClient = createHttpClient();
return commonHttpClientPost(reqUrl, reqBodyParams, contentType, encoding, headerMap, httpClient);
}
/**
*
* @Description commonHttpClientPost
* @Date 2017年8月1日 上午10:34:43
* @param reqUrl
* @param reqBodyParams
* @param contentType
* @param encoding
* @param headerMap
* @param httpClient
* @return 參數(shù)
* @return String 返回類型
*/
private static String commonHttpClientPost(String reqUrl, Map<String, Object> reqBodyParams, String contentType, String encoding, Map<String, Object> headerMap, CloseableHttpClient httpClient) {
String result ="";
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(reqUrl);
String reqParamStr = "";
/*設(shè)置請求頭屬性和值 */
if(headerMap!=null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
Object value = headerMap.get(key);
//如: httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader(key,String.valueOf(value));
}
}
reqParamStr = reqParamStr(reqBodyParams, encoding, reqParamStr);
httpPost.setConfig(requestConfig);
if(reqParamStr!=null){
StringEntity stringEntity = new StringEntity(reqParamStr.toString(),(encoding==null||"".equals(encoding)?"utf-8":encoding));//解決中文亂碼問題
if(encoding!=null && encoding!=""){
stringEntity.setContentEncoding(encoding);
}
if(contentType!=null && contentType!=""){
stringEntity.setContentType(contentType);
}
httpPost.setEntity(stringEntity);
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode()==200) {
String buffer = IoUtils.getInputStream(entity.getContent());
logger.info(getCurrentClassName()+"#commonHttpClientPost,***reqUrl***:"+reqUrl+",***Response content*** : " + buffer.toString());
return buffer.toString();//返回
}else{
logger.error("commonHttpClientPost的entity對象為空");
return result;
}
} catch (IOException e) {
logger.error("HttpUrlPost出現(xiàn)異常,異常信息為:"+e.getMessage());
e.printStackTrace();
} finally {
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* @Description httpClientGet
* @Date 2017年5月22日 下午3:57:03
* @param apiUrl
* @param json
* @param contentType
* @return String 返回類型
* @throws
*/
public static String createHttpsGet(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {
CloseableHttpClient httpClient = createHttpClient();
String httpStr = commonHttpClientGet(reqUrl, reqBodyParams, encoding, headerMap, httpClient);
return httpStr;
}
/**
* @Description commonHttpClientGet
* @Date 2017年8月1日 上午10:35:09
* @param reqUrl
* @param reqBodyParams
* @param encoding
* @param headerMap
* @param httpClient
* @return 參數(shù)
* @return String 返回類型
*/
private static String commonHttpClientGet(String reqUrl, Map<String, Object> reqBodyParams, String encoding, Map<String, Object> headerMap, CloseableHttpClient httpClient) {
String httpStr = null;
String reqParamStr = "";
CloseableHttpResponse response = null;
try {
reqParamStr = reqParamStr(reqBodyParams, encoding, reqParamStr);
HttpGet httpGet = null;
if(ObjectUtil.isNotEmpty(reqParamStr)){
System.out.println(reqUrl+"?"+reqParamStr);
httpGet = new HttpGet(reqUrl+"?"+reqParamStr);
}else{
httpGet = new HttpGet(reqUrl);
}
/*設(shè)置請求頭屬性和值 */
if(headerMap!=null && !headerMap.isEmpty()){
for (String key : headerMap.keySet()) {
Object value = headerMap.get(key);
//如: httpPost.addHeader("Content-Type", "application/json");
httpGet.addHeader(key,String.valueOf(value));
}
}
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode()==200) {
httpStr = EntityUtils.toString(entity,encoding);
logger.info(getCurrentClassName()+"#commonHttpClientGet,***reqUrl:***"+reqUrl+",Response content*** : " + httpStr);
}else{
httpStr = null;
logger.error("httpClientGet的entity對象為空");
}
} catch (IOException e) {
logger.error("HttpUrlPost出現(xiàn)異常纬向,異常信息為:"+e.getMessage());
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
public static String createHttpPost(String url, List<BasicNameValuePair> params) {
try {
CloseableHttpClient httpClient = createHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine()!=null && httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String retMsg = EntityUtils.toString(httpResponse.getEntity(), DEFAULT_ENCODING);
if(!ObjectUtil.isEmpty(retMsg)){
return retMsg;
}
}else{
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String getCurrentClassName(){
return HttpClientUtil.class.getName();
}
}
- SSLContextSecurity
/**
* @Description SSLContextSecurity上下文安全處理類
*
*
* @ClassName SSLContextSecurity
* @Date 2017年6月6日 上午10:45:09
* @Author liangjilong
* @Copyright (c) All Rights Reserved, 2017.
*/
public class SSLContextSecurity {
/**
* 繞過驗(yàn)證
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLSocketFactory createIgnoreVerifySSL(String sslVersion) throws NoSuchAlgorithmException, KeyManagementException {
//SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
SSLContext sc = SSLContext.getInstance(sslVersion); //"TLSv1.2"
// 實(shí)現(xiàn)一個X509TrustManager接口择浊,用于繞過驗(yàn)證,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, new SecureRandom());
/***
* 如果 hostname in certificate didn't match的話就給一個默認(rèn)的主機(jī)驗(yàn)證
*/
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return sc.getSocketFactory();
}
/**
* @Description 根據(jù)版本號進(jìn)行獲取協(xié)議項(xiàng)下
* @Author liangjilong
* @Date 2017年6月6日 上午11:15:27
* @param tslVerision
* @return 參數(shù)
* @return String[] 返回類型
* @throws
*/
public static String[] getProtocols(String tslVerision){
try {
SSLContext context = SSLContext.getInstance(tslVerision);
context.init(null, null, null);
SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket();
String [] protocols = socket.getSupportedProtocols();
for (int i = 0; i < protocols.length; i++) {
System.out.println(" " + protocols[i]);
}
return socket.getEnabledProtocols();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}