RestTemplate リクエストヘッダー/ボディ設定方法

RestTemplateにリクエストヘッダーとリクエストボディを設定するには、exchange()メソッドを使用してHTTPリクエストを送信します。HttpEntityオブジェクトを作成し、リクエストヘッダーとリクエストボディを設定し、exchange()メソッドのパラメーターとして渡すことができます。以下は例のコードです:

RestTemplate restTemplate = new RestTemplate();

// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

// 设置请求体
String requestBody = "{\"key1\": \"value1\", \"key2\": \"value2\"}";

// 创建HttpEntity对象,设置请求头和请求体
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

// 发送POST请求
ResponseEntity<String> responseEntity = restTemplate.exchange("http://api.example.com", HttpMethod.POST, requestEntity, String.class);

String responseBody = responseEntity.getBody();
System.out.println(responseBody);

上記のコードでは、まずRestTemplateオブジェクトを作成しました。そして、リクエストヘッダーとリクエストボディを設定し、HttpEntityオブジェクトを作成しました。最後に、exchange()メソッドを使用してPOSTリクエストを送信し、レスポンスボディを取得しました。

bannerAds