홍호나 2022. 5. 11. 09:56

restTemplate 상태코드 가져오기

https://gist.github.com/ktarou/a875e84d0a65dce99dd38e307fe016e1

 

public class HandleHttpServerErrorException {
private ObjectMapper objectMapper = new ObjectMapper();
  
public ResponseEntity<Map<String, Object>> handleRestTemplateCall() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("param1", "1");
parameters.add("param2", "2");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(parameters, headers);

try {
Map<string, object=""> message = restTemplate.postForEntity("http://www.example.com/rest", </string,>
request, new TypeReference<Map<String, Object>>() {});
return ResponseEntity.ok().body(message);
}
catch (HttpServerErrorException e) {
String responseBody = e.getResponseBodyAsString();
Map<String, Object> resp = objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {});
return ResponseEntity.status(e.getRawStatusCode()).body(resp);
}
}
}