1 回答

TA貢獻1735條經(jīng)驗 獲得超5個贊
RestTemplate 不支持 200 以外的 HTTP 代碼。一種解決方案是使用 HttpStatusCodeException 捕獲其他類型的 HTTP 代碼。
try {
restTemplate.getForObject("https://api.twitter.com/1.1/followers/ids.json", Object.class);
}
} catch (HttpStatusCodeException e) {
if (e.getStatusCode() == HttpStatus.BAD_REQUEST) { // Http code 400
String bodyResponse = e.getResponseBodyAsString();
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(bodyResponse, Object.class);
} catch (Exception exception) {
}
}
如果你使用 Spring,你可以像這樣配置 Bean RestTemplate:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
我希望它有幫助。
添加回答
舉報