在Spring Boot項目中發起HTTP請求的方法
在Spring Boot項目中,有幾種常用的方式可以發起HTTP請求,以下是主要的幾種方法:
1. 使用RestTemplate (Spring 5之前的主流方式)
// 需要先注入RestTemplate
@Autowired
private RestTemplate restTemplate;public void makeRequest() {// GET請求ResponseEntity<String> response = restTemplate.getForEntity("https://api.example.com/data", String.class);// POST請求HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> request = new HttpEntity<>("{\"key\":\"value\"}", headers);ResponseEntity<String> response = restTemplate.postForEntity("https://api.example.com/data", request, String.class);
}
2. 使用WebClient (Spring 5+推薦的響應式方式)
// 需要添加spring-boot-starter-webflux依賴
WebClient webClient = WebClient.create();// GET請求
Mono<String> response = webClient.get().uri("https://api.example.com/data").retrieve().bodyToMono(String.class);// POST請求
Mono<String> response = webClient.post().uri("https://api.example.com/data").contentType(MediaType.APPLICATION_JSON).bodyValue("{\"key\":\"value\"}").retrieve().bodyToMono(String.class);
3. 使用HttpClient (Java 11+內置)
HttpClient client = HttpClient.newHttpClient();// GET請求
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.example.com/data")).build();// POST請求
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.example.com/data")).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}")).build();// 發送請求
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
4. 使用Feign Client (聲明式REST客戶端)
// 需要添加spring-cloud-starter-openfeign依賴
@FeignClient(name = "exampleClient", url = "https://api.example.com")
public interface ExampleClient {@GetMapping("/data")String getData();@PostMapping("/data")String postData(@RequestBody String body);
}// 使用
@Autowired
private ExampleClient exampleClient;public void makeRequest() {String response = exampleClient.getData();
}
5. 使用第三方庫如OkHttp或Apache HttpClient
OkHttp示例:
OkHttpClient client = new OkHttpClient();// GET請求
Request request = new Request.Builder().url("https://api.example.com/data").build();// POST請求
RequestBody body = RequestBody.create("{\"key\":\"value\"}", MediaType.parse("application/json"));
Request request = new Request.Builder().url("https://api.example.com/data").post(body).build();// 發送請求
Response response = client.newCall(request).execute();
Apache HttpClient示例:
CloseableHttpClient httpClient = HttpClients.createDefault();// GET請求
HttpGet httpGet = new HttpGet("https://api.example.com/data");// POST請求
HttpPost httpPost = new HttpPost("https://api.example.com/data");
StringEntity entity = new StringEntity("{\"key\":\"value\"}");
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");// 發送請求
CloseableHttpResponse response = httpClient.execute(httpPost);
選擇建議
- 對于新項目,推薦使用 WebClient (響應式) 或 HttpClient (Java內置)
- 如果使用Spring Cloud,Feign Client 是一個很好的選擇
- RestTemplate 雖然仍可使用,但已進入維護模式,不推薦新項目使用
- 需要更多控制時,可以考慮 OkHttp 或 Apache HttpClient