1. 程式人生 > 其它 >Java HttpClient做http請求(form-data和json兩種)

Java HttpClient做http請求(form-data和json兩種)

一、匯入依賴

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.5.13</version>
</dependency>

二、方法

package cn.com.wind.utils;

import cn.com.wind.exception.TranspondException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; 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.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.nio.charset.StandardCharsets; /** * @Author qymeng * @Date 2021/10/25 * @Description 介面轉發的工具類 */ @Slf4j public class TranspondUtils { /** * POST請求 * * @param json 請求的json體 * @param url 請求的url地址 */ public static String doPost(String json, String url) { HttpClient httpClient = new HttpClient(); // 設定http連線主機服務超時時間 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(35000); PostMethod postMethod = new PostMethod(url); // 設定post請求超時 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 設定請求重試機制,預設重試次數:3次,引數設定為true,重試機制可用,false相反 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); String result = null; try { RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8"); //請求頭資訊 postMethod.setRequestHeader("Content-Type", "application/json"); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { // 獲取響應輸入流 InputStream inStream = postMethod.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8)); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) strber.append(line).append("\n"); inStream.close(); result = strber.toString(); } else { throw new TranspondException("請求服務端失敗,狀態碼不為200"); } } catch (IOException e) { throw new TranspondException("請求服務端失敗,地址為:" + url); } catch (IllegalStateException e) { throw new TranspondException("url地址不正確,該地址為:" + url); } catch (Exception e) { throw new TranspondException("其他異常"); } return result; } public static String doPost(Object json, String url) { String s = JSON.toJSONString(json); return doPost(s, url); } /** * form-data 傳送檔案 * @param url * @param file * @return */ public static String httpPostFile(String url, MultipartFile file){ CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); String filename = file.getOriginalFilename(); builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, filename); // StringBody fileName = new StringBody("檔名稱", ContentType.MULTIPART_FORM_DATA); // builder.addPart("fileName", fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e){ e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * GET請求 * * @param url 請求的url地址 */ public static String doGet(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { // 通過址預設配置建立一個httpClient例項 httpClient = HttpClients.createDefault(); // 建立httpGet遠端連線例項 HttpGet httpGet = new HttpGet(url); // 設定配置請求引數 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連線主機服務超時時間 .setConnectionRequestTimeout(35000)// 請求超時時間 .setSocketTimeout(60000)// 資料讀取超時時間 .build(); // 為httpGet例項設定配置 httpGet.setConfig(requestConfig); // 執行get請求得到返回物件 response = httpClient.execute(httpGet); // 通過返回物件獲取返回資料 HttpEntity entity = response.getEntity(); // 通過EntityUtils中的toString方法將結果轉換為字串 result = EntityUtils.toString(entity); // log.info("請求伺服器成功"); } catch (IOException e) { throw new TranspondException("GET請求異常, URL為:" + url); } finally { // 關閉資源 if (null != response) { try { response.close(); } catch (IOException e) { throw new TranspondException("關閉CloseableHttpResponse時出現異常, URL為:" + url); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { throw new TranspondException("關閉CloseableHttpClient時出現異常, URL為:" + url); } } } return result; } public static JSONObject doGetJson(String url) { return JSONObject.parseObject(doGet(url)); } /** * 檢測執行備用方案,檢測http狀態碼 * @param json * @param url * @return */ public static boolean isRunning(String json, String url){ HttpClient httpClient = new HttpClient(); // 設定http連線主機服務超時時間 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(35000); PostMethod postMethod = new PostMethod(url); // 設定post請求超時 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 設定請求重試機制,預設重試次數:3次,引數設定為true,重試機制可用,false相反 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); try { RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8"); //請求頭資訊 postMethod.setRequestHeader("Content-Type", "application/json"); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); return postMethod.getStatusCode() == HttpStatus.SC_OK; } catch (IOException e) { throw new TranspondException("請求服務端失敗,地址為:" + url); } catch (IllegalStateException e) { throw new TranspondException("url地址不正確,該地址為:" + url); } catch (Exception e) { throw new TranspondException("其他異常"); } } }