HttpClient工具类
生活随笔
收集整理的這篇文章主要介紹了
HttpClient工具类
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
HttpClient工具類(lèi)
package cn.sh.steven.httpclient;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; 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.client.utils.URLEncodedUtils; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;public class HttpToolUtils {private static final Logger log = LoggerFactory.getLogger(HttpToolUtils.class);private static RequestConfig requestConfig;static {requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectionRequestTimeout(5000).setConnectTimeout(5000).build();}/*** 發(fā)送HTTP_GET請(qǐng)求** @param reqURL 請(qǐng)求地址(含參數(shù))* @param decodeCharset 解碼字符集,解析響應(yīng)數(shù)據(jù)時(shí)用之,其為null時(shí)默認(rèn)采用UTF-8解碼* @return 遠(yuǎn)程主機(jī)響應(yīng)正文*/public static String sendGetRequest(String reqURL, String decodeCharset) {long responseLength = 0; //響應(yīng)長(zhǎng)度CloseableHttpClient httpClient = HttpClients.createDefault();String responseContent = null; //響應(yīng)內(nèi)容HttpGet httpGet = new HttpGet(reqURL); //創(chuàng)建org.apache.http.client.methods.HttpGettry {HttpResponse response = httpClient.execute(httpGet); //執(zhí)行GET請(qǐng)求HttpEntity entity = response.getEntity(); //獲取響應(yīng)實(shí)體if (null != entity) {responseLength = entity.getContentLength();responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);EntityUtils.consume(entity); //Consume response content}System.out.println("請(qǐng)求地址: " + httpGet.getURI());System.out.println("響應(yīng)狀態(tài): " + response.getStatusLine());System.out.println("響應(yīng)長(zhǎng)度: " + responseLength);System.out.println("響應(yīng)內(nèi)容: " + responseContent);} catch (ClientProtocolException e) {log.debug("該異常通常是協(xié)議錯(cuò)誤導(dǎo)致,比如構(gòu)造HttpGet對(duì)象時(shí)傳入的協(xié)議不對(duì)(將'http'寫(xiě)成'htp')或者服務(wù)器端返回的內(nèi)容不符合HTTP協(xié)議要求等,堆棧信息如下", e);} catch (ParseException e) {log.debug(e.getMessage(), e);} catch (IOException e) {log.debug("該異常通常是網(wǎng)絡(luò)原因引起的,堆棧信息如下", e);} finally {httpGet.releaseConnection(); //關(guān)閉連接,釋放資源}return responseContent;}/*** @param url url地址* @param jsonParam 參數(shù)* @return JSONObject*/public static JSONObject httpPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post請(qǐng)求返回結(jié)果JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);// 設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解決中文亂碼問(wèn)題StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");httpPost.setEntity(entity);}CloseableHttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String s = EntityUtils.toString(response.getEntity(), "utf-8");jsonResult = JSONObject.parseObject(s);// 請(qǐng)求發(fā)送成功,并得到響應(yīng)log.info("post請(qǐng)求成功,響應(yīng)數(shù)據(jù):{}", jsonResult);}} catch (IOException e) {log.error("post請(qǐng)求提交失敗,異常信息:{}", e.getStackTrace());} finally {httpPost.releaseConnection();}return jsonResult;}/*** @param url url地址* @param jsonParam 參數(shù)* @return String*/public static String sendPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post請(qǐng)求返回結(jié)果String s = null;HttpPost httpPost = new HttpPost(url);// 設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解決中文亂碼問(wèn)題StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");httpPost.setEntity(entity);}CloseableHttpResponse response = httpClient.execute(httpPost);log.info("調(diào)用接口返回response{}", response);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {s = EntityUtils.toString(response.getEntity(), "utf-8");// 請(qǐng)求發(fā)送成功,并得到響應(yīng)log.info("post請(qǐng)求成功,響應(yīng)數(shù)據(jù):{}", s);}} catch (IOException e) {log.error("post請(qǐng)求提交失敗,異常信息:{}", e);} finally {httpPost.releaseConnection();}return s;}/*** 發(fā)送HTTP_POST請(qǐng)求** @param isEncoder 用于指明請(qǐng)求數(shù)據(jù)是否需要UTF-8編碼,true為需要* @see //該方法為<code>sendPostRequest(String,String,boolean,String,String)</code>的簡(jiǎn)化方法* @see //該方法在對(duì)請(qǐng)求數(shù)據(jù)的編碼和響應(yīng)數(shù)據(jù)的解碼時(shí),所采用的字符集均為UTF-8* @see //當(dāng)<code>isEncoder=true</code>時(shí),其會(huì)自動(dòng)對(duì)<code>sendData</code>中的[中文][|][ ]等特殊字符進(jìn)行<code>URLEncoder.encode(string,"UTF-8")</code>*/public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) {return sendPostRequest(reqURL, sendData, isEncoder, null, null);}/*** 發(fā)送HTTP_POST請(qǐng)求** @param reqURL 請(qǐng)求地址* @param sendData 請(qǐng)求參數(shù),若有多個(gè)參數(shù)則應(yīng)拼接成param11=value11&22=value22&33=value33的形式后,傳入該參數(shù)中* @param isEncoder 請(qǐng)求數(shù)據(jù)是否需要encodeCharset編碼,true為需要* @param encodeCharset 編碼字符集,編碼請(qǐng)求數(shù)據(jù)時(shí)用之,其為null時(shí)默認(rèn)采用UTF-8解碼* @param decodeCharset 解碼字符集,解析響應(yīng)數(shù)據(jù)時(shí)用之,其為null時(shí)默認(rèn)采用UTF-8解碼* @return 遠(yuǎn)程主機(jī)響應(yīng)正文* @see //該方法會(huì)自動(dòng)關(guān)閉連接,釋放資源* @see //當(dāng)<code>isEncoder=true</code>時(shí),其會(huì)自動(dòng)對(duì)<code>sendData</code>中的[中文][|][ ]等特殊字符進(jìn)行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader("X-APP-ID", "eb77fe57515a9d8efe137278181e08a4");httpPost.setHeader("X-APP-KEY", "2f4bb04c0f4aa02c85e91a7c64a41f52");httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");try {if (isEncoder) {List<NameValuePair> formParams = new ArrayList<NameValuePair>();for (String str : sendData.split("&")) {formParams.add(new BasicNameValuePair(str.substring(0, str.indexOf("=")), str.substring(str.indexOf("=") + 1)));}httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset == null ? "UTF-8" : encodeCharset)));} else {String s;StringEntity stringEntity = new StringEntity(sendData);stringEntity.setContentType("text/json");httpPost.setEntity(stringEntity);}HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (null != entity) {responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);EntityUtils.consume(entity);}} catch (Exception e) {log.info("與[" + reqURL + "]通信過(guò)程中發(fā)生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 發(fā)送HTTP_POST請(qǐng)求** @param reqURL 請(qǐng)求地址* @param sendData 請(qǐng)求參數(shù),若有多個(gè)參數(shù)則應(yīng)拼接成param11=value11&22=value22&33=value33的形式后,傳入該參數(shù)中* @return 遠(yuǎn)程主機(jī)響應(yīng)正文* @see //該方法會(huì)自動(dòng)關(guān)閉連接,釋放資源* @see //當(dāng)<code>isEncoder=true</code>時(shí),其會(huì)自動(dòng)對(duì)<code>sendData</code>中的[中文][|][ ]等特殊字符進(jìn)行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, String sendData) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");try {StringEntity stringEntity = new StringEntity(sendData,"UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(90000).setConnectionRequestTimeout(90000).setSocketTimeout(90000).build();httpPost.setConfig(requestConfig);HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();if (null != entity) {responseContent = EntityUtils.toString(entity, "UTF-8");EntityUtils.consume(entity);}} catch (Exception e) {log.info("與[" + reqURL + "]通信過(guò)程中發(fā)生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 發(fā)送HTTP_POST請(qǐng)求** @param reqURL 請(qǐng)求地址* @param params 請(qǐng)求參數(shù)* @return 遠(yuǎn)程主機(jī)響應(yīng)正文* @see //該方法會(huì)自動(dòng)關(guān)閉連接,釋放資源* @see //該方法會(huì)自動(dòng)對(duì)<code>params</code>中的[中文][|][ ]等特殊字符進(jìn)行<code>URLEncoder.encode(string,encodeCharset)</code>*/public static String sendPostRequest(String reqURL, Map<String, String> params) {String responseContent = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(reqURL);httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //創(chuàng)建參數(shù)隊(duì)列for (Map.Entry<String, String> entry : params.entrySet()) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}try {httpPost.setEntity(new UrlEncodedFormEntity(formParams, "utf-8"));log.info("http遠(yuǎn)程調(diào)用開(kāi)始……");HttpResponse response = httpClient.execute(httpPost);log.info("http遠(yuǎn)程調(diào)用返回:{}", JSON.toJSONString(response));HttpEntity entity = response.getEntity();log.info("遠(yuǎn)程調(diào)用返回entity:{}", JSON.toJSONString(entity));if (null != entity) {responseContent = EntityUtils.toString(entity, "utf-8");log.info("遠(yuǎn)程調(diào)用返回responseContent:{}", JSON.toJSONString(responseContent));EntityUtils.consume(entity);}} catch (Exception e) {log.info("與[" + reqURL + "]通信過(guò)程中發(fā)生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}}總結(jié)
以上是生活随笔為你收集整理的HttpClient工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: HttpClient在传参和返回结果的中
- 下一篇: 解决springboot配置jackso