1 回答

TA贡献1735条经验 获得超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());
}
我希望它有帮助。
添加回答
举报