1、起一個 springboot 程式做 http 測驗:
@GetMapping("/http/get")
public ResponseEntity<String> testHttpGet(@RequestParam("param") String param) {
System.out.println(param);
return ResponseEntity.ok("---------> revive http get request --------->");
}
@PostMapping("/http/post")
public ResponseEntity<String> testHttpPost(@RequestBody List<Object> body) {
System.out.println(body);
return ResponseEntity.ok("---------> receive http post request --------->");
}
2、寫一個 HttpURLConnection 自定義客戶端
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Map; public class MyHttpClient { private final HttpURLConnection connection; private MyHttpClient(String url, Map<String, String> params) throws IOException { connection = buildConnection(url, params); } private MyHttpClient(String url, Map<String, String> params, String jsonBody) throws IOException { connection = buildConnection(url, params); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); connection.setDoOutput(true); try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.writeBytes(jsonBody); outputStream.flush(); } } public static MyHttpClient get(String url, Map<String, String> params) throws IOException { return new MyHttpClient(url, params); } public static MyHttpClient post(String url, Map<String, String> params, String jsonBody) throws IOException { return new MyHttpClient(url, params, jsonBody); } /** * 創建 http 連接 * * @param url 請求路徑 * @param params 請求引數,可以為空 * @return http 連接 */ private HttpURLConnection buildConnection(String url, Map<String, String> params) throws IOException { String requestParams = getParamsString(params); return (HttpURLConnection) new URL(requestParams != null ? url + "?" + requestParams : url).openConnection(); } /** * 獲取 http 請求回應結果 * * @return 回應結果,失敗拋例外 */ public String getResponse() throws IOException { int responseCode = connection.getResponseCode(); if (responseCode >= HttpURLConnection.HTTP_OK && responseCode < HttpURLConnection.HTTP_MULT_CHOICE) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); connection.disconnect(); return response.toString(); } else { connection.disconnect(); InputStream errorStream = connection.getErrorStream(); if (errorStream == null) { throw new ConnectException("request fail"); } throw new ConnectException(new String(errorStream.readAllBytes(), StandardCharsets.UTF_8)); } } /** * 拼接請求引數 * * @param params 引數 map * @return 請求引數字串 */ public static String getParamsString(Map<String, String> params) { if (params == null || params.isEmpty()) { return null; } StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)); result.append("="); result.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); result.append("&"); } String resultString = result.toString(); return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; } }
3、測驗 get 和 post 請求
public static void main(String[] args) throws IOException { MyHttpClient myHttpClient = MyHttpClient.get("http://127.0.0.1:8083/springboot/http/get", Map.of("param", "1")); String resultGet = myHttpClient.getResponse(); System.out.println(resultGet); MyHttpClient httpClient = MyHttpClient.post("http://127.0.0.1:8083/springboot/http/post", null, "[1,2,3,4,5]"); String resultPost = httpClient.getResponse(); System.out.println(resultPost); }
4、控制臺輸出結果
---------> revive http get request --------->
---------> receive http post request --------->
Process finished with exit code 0
中間遇到一些坑,經常以為 http 會有方法像 openfeign 那樣傳入請求引數,忽略了路徑拼接,
啟動的 springboot 接收的 post 的請求體為 List 型別,且 Content-Type 是 json,在測驗 post 請求時一直報錯,看了 spring 控制臺才發現 json 轉物件封裝 沒對上,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/550781.html
標籤:其他
下一篇:返回列表
