在使用RestTemplate
發送HTTP請求時,你可以通過不同的方式發送JSON或表單數據(application/x-www-form-urlencoded
)。同時,處理接口錯誤狀態碼(如400)和返回null
的情況也是很重要的。以下是一些示例代碼,展示了如何使用RestTemplate
發送不同格式的數據,并處理錯誤。
發送JSON數據
要發送JSON數據,你需要將你的對象轉換為JSON字符串,并設置正確的Content-Type
頭為application/json
。你可以使用HttpEntity
和HttpHeaders
來構建請求,并使用RestTemplate
的postForObject
或postForEntity
方法發送請求。
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;// ...RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);// 假設你有一個名為MyObject的對象,你想將它發送為JSON
MyObject myObject = new MyObject();
// ... 設置myObject的屬性String jsonPayload = new ObjectMapper().writeValueAsString(myObject); // 使用Jackson庫將對象轉換為JSON字符串HttpEntity<String> entity = new HttpEntity<>(jsonPayload, headers);String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);if (response.getStatusCode().is2xxSuccessful()) {// 處理成功的響應
} else {// 處理錯誤,例如狀態碼400if (response.getStatusCode() == HttpStatus.BAD_REQUEST) {// 錯誤處理邏輯,例如打印錯誤消息或記錄日志System.err.println("Bad request: " + response.getBody());}// 注意:如果響應體為null,response.getBody()將返回null
}
發送表單數據
要發送表單數據,你可以使用MultiValueMap
來存儲表單字段和值,并使用formHttpMessageConverter
。
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;// ...RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key1", "value1");
map.add("key2", "value2");HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);// 錯誤處理與上述相同
處理接口錯誤狀態碼400和null響應體
如上所示,你可以通過檢查ResponseEntity
的getStatusCode
方法來處理不同的HTTP狀態碼。對于狀態碼400(Bad Request),你可以根據需要執行特定的錯誤處理邏輯。
如果響應體為null,response.getBody()
將返回null。在這種情況下,你可能需要根據你的業務邏輯來決定如何處理它。例如,你可以記錄一個錯誤消息,或者拋出一個異常來指示調用者發生了問題。
請注意,上述示例使用了Jackson庫來將對象轉換為JSON字符串。如果你的項目中還沒有包含Jackson,你需要在你的pom.xml
或build.gradle
中添加相應的依賴項。