日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HttpClient工具类

發布時間:2024/10/6 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HttpClient工具类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

HttpClient工具類

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();}/*** 發送HTTP_GET請求** @param reqURL 請求地址(含參數)* @param decodeCharset 解碼字符集,解析響應數據時用之,其為null時默認采用UTF-8解碼* @return 遠程主機響應正文*/public static String sendGetRequest(String reqURL, String decodeCharset) {long responseLength = 0; //響應長度CloseableHttpClient httpClient = HttpClients.createDefault();String responseContent = null; //響應內容HttpGet httpGet = new HttpGet(reqURL); //創建org.apache.http.client.methods.HttpGettry {HttpResponse response = httpClient.execute(httpGet); //執行GET請求HttpEntity entity = response.getEntity(); //獲取響應實體if (null != entity) {responseLength = entity.getContentLength();responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);EntityUtils.consume(entity); //Consume response content}System.out.println("請求地址: " + httpGet.getURI());System.out.println("響應狀態: " + response.getStatusLine());System.out.println("響應長度: " + responseLength);System.out.println("響應內容: " + responseContent);} catch (ClientProtocolException e) {log.debug("該異常通常是協議錯誤導致,比如構造HttpGet對象時傳入的協議不對(將'http'寫成'htp')或者服務器端返回的內容不符合HTTP協議要求等,堆棧信息如下", e);} catch (ParseException e) {log.debug(e.getMessage(), e);} catch (IOException e) {log.debug("該異常通常是網絡原因引起的,堆棧信息如下", e);} finally {httpGet.releaseConnection(); //關閉連接,釋放資源}return responseContent;}/*** @param url url地址* @param jsonParam 參數* @return JSONObject*/public static JSONObject httpPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post請求返回結果JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);// 設置請求和傳輸超時時間httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解決中文亂碼問題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);// 請求發送成功,并得到響應log.info("post請求成功,響應數據:{}", jsonResult);}} catch (IOException e) {log.error("post請求提交失敗,異常信息:{}", e.getStackTrace());} finally {httpPost.releaseConnection();}return jsonResult;}/*** @param url url地址* @param jsonParam 參數* @return String*/public static String sendPost(String url, JSONObject jsonParam) {CloseableHttpClient httpClient = HttpClients.createDefault();// post請求返回結果String s = null;HttpPost httpPost = new HttpPost(url);// 設置請求和傳輸超時時間httpPost.setConfig(requestConfig);try {if (null != jsonParam) {httpPost.setHeader("Content-type", "application/json");// 解決中文亂碼問題StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");httpPost.setEntity(entity);}CloseableHttpResponse response = httpClient.execute(httpPost);log.info("調用接口返回response{}", response);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {s = EntityUtils.toString(response.getEntity(), "utf-8");// 請求發送成功,并得到響應log.info("post請求成功,響應數據:{}", s);}} catch (IOException e) {log.error("post請求提交失敗,異常信息:{}", e);} finally {httpPost.releaseConnection();}return s;}/*** 發送HTTP_POST請求** @param isEncoder 用于指明請求數據是否需要UTF-8編碼,true為需要* @see //該方法為<code>sendPostRequest(String,String,boolean,String,String)</code>的簡化方法* @see //該方法在對請求數據的編碼和響應數據的解碼時,所采用的字符集均為UTF-8* @see //當<code>isEncoder=true</code>時,其會自動對<code>sendData</code>中的[中文][|][ ]等特殊字符進行<code>URLEncoder.encode(string,"UTF-8")</code>*/public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) {return sendPostRequest(reqURL, sendData, isEncoder, null, null);}/*** 發送HTTP_POST請求** @param reqURL 請求地址* @param sendData 請求參數,若有多個參數則應拼接成param11=value11&22=value22&33=value33的形式后,傳入該參數中* @param isEncoder 請求數據是否需要encodeCharset編碼,true為需要* @param encodeCharset 編碼字符集,編碼請求數據時用之,其為null時默認采用UTF-8解碼* @param decodeCharset 解碼字符集,解析響應數據時用之,其為null時默認采用UTF-8解碼* @return 遠程主機響應正文* @see //該方法會自動關閉連接,釋放資源* @see //當<code>isEncoder=true</code>時,其會自動對<code>sendData</code>中的[中文][|][ ]等特殊字符進行<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 + "]通信過程中發生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 發送HTTP_POST請求** @param reqURL 請求地址* @param sendData 請求參數,若有多個參數則應拼接成param11=value11&22=value22&33=value33的形式后,傳入該參數中* @return 遠程主機響應正文* @see //該方法會自動關閉連接,釋放資源* @see //當<code>isEncoder=true</code>時,其會自動對<code>sendData</code>中的[中文][|][ ]等特殊字符進行<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 + "]通信過程中發生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}/*** 發送HTTP_POST請求** @param reqURL 請求地址* @param params 請求參數* @return 遠程主機響應正文* @see //該方法會自動關閉連接,釋放資源* @see //該方法會自動對<code>params</code>中的[中文][|][ ]等特殊字符進行<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>(); //創建參數隊列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遠程調用開始……");HttpResponse response = httpClient.execute(httpPost);log.info("http遠程調用返回:{}", JSON.toJSONString(response));HttpEntity entity = response.getEntity();log.info("遠程調用返回entity:{}", JSON.toJSONString(entity));if (null != entity) {responseContent = EntityUtils.toString(entity, "utf-8");log.info("遠程調用返回responseContent:{}", JSON.toJSONString(responseContent));EntityUtils.consume(entity);}} catch (Exception e) {log.info("與[" + reqURL + "]通信過程中發生異常,堆棧信息如下", e);} finally {httpPost.releaseConnection();}return responseContent;}}

總結

以上是生活随笔為你收集整理的HttpClient工具类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。