HttpClient4.3 post與get請求工具類完整示例
阿新 • • 發佈:2019-01-02
整個工具類程式碼如下所示,可直接使用!
import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; 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.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; /** * HttpClient4.3工具類 * * @author tech * @date 2016-03-29 * */ public class HttpClientUtils { private static Logger logger = LoggerFactory .getLogger(HttpClientUtils.class); // 日誌記錄 /** * post請求傳輸json引數 * * @param url * url地址 * @param json * 引數 * @return */ public static JSONObject httpPost(String url, JSONObject jsonParam) { // post請求返回結果 CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(url); // 設定請求和傳輸超時時間 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig); try { if (null != jsonParam) { // 解決中文亂碼問題 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); } CloseableHttpResponse result = httpClient.execute(httpPost); //請求傳送成功,並得到響應 if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String str = ""; try { //讀取伺服器返回過來的json字串資料 str = EntityUtils.toString(result.getEntity(), "utf-8"); //把json字串轉換成json物件 jsonResult = JSONObject.parseObject(str); } catch (Exception e) { logger.error("post請求提交失敗:" + url, e); } } } catch (IOException e) { logger.error("post請求提交失敗:" + url, e); } finally { httpPost.releaseConnection(); } return jsonResult; } /** * post請求傳輸String引數 * 例如:name=Jack&sex=1&type=2 * Content-type:application/x-www-form-urlencoded * @param url * url地址 * @param strParam * 引數 * @param noNeedResponse * 不需要返回結果 * @return */ public static JSONObject httpPost(String url, String strParam) { // post請求返回結果 CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(url); // 設定請求和傳輸超時時間 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(2000).setConnectTimeout(2000).build(); httpPost.setConfig(requestConfig); try { if (null != strParam) { // 解決中文亂碼問題 StringEntity entity = new StringEntity(strParam,"utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); } CloseableHttpResponse result = httpClient.execute(httpPost); //請求傳送成功,並得到響應 if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String str = ""; try { //讀取伺服器返回過來的json字串資料 str = EntityUtils.toString(result.getEntity(), "utf-8"); //把json字串轉換成json物件 jsonResult = JSONObject.parseObject(str); } catch (Exception e) { logger.error("post請求提交失敗:" + url, e); } } } catch (IOException e) { logger.error("post請求提交失敗:" + url, e); } finally { httpPost.releaseConnection(); } return jsonResult; } /** * 傳送get請求 * * @param url * 路徑 * @return */ public static JSONObject httpGet(String url) { // get請求返回結果 JSONObject jsonResult = null; CloseableHttpClient client = HttpClients.createDefault(); // 傳送get請求 HttpGet request = new HttpGet(url); // 設定請求和傳輸超時時間 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(2000).setConnectTimeout(2000).build(); request.setConfig(requestConfig); try { CloseableHttpResponse response = client.execute(request); //請求傳送成功,並得到響應 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //讀取伺服器返回過來的json字串資料 HttpEntity entity = response.getEntity(); String strResult = EntityUtils.toString(entity, "utf-8"); //把json字串轉換成json物件 jsonResult = JSONObject.parseObject(strResult); } else { logger.error("get請求提交失敗:" + url); } } catch (IOException e) { logger.error("get請求提交失敗:" + url, e); } finally { request.releaseConnection(); } return jsonResult; } public static void main(String[] args) { //TODO 測試程式碼 } }