为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Rest 模板与 https 请求的单元测试

Spring Rest 模板与 https 请求的单元测试

幕布斯7119047 2023-12-21 10:45:38
我在使用休息模板期间遇到异常,但在单元测试中没有遇到异常 - 有什么想法吗?    @GetMapping("/webapp/git")    public Object hit() {        return restTemplate.getForObject("https://api.twitter.com/1.1/followers/ids.json", Object.class);//          return Unirest.get("https://api.twitter.com/1.1/followers/ids.json").asString().getBody();    }org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:79) ~[spring-web-5.2.0.RELEASE.jar:5.2.0.RELEASE]    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:123) ~[spring-web-5.2.0.RELEASE.jar:5.2.0.RELEASE]    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102) ~[spring-web-5.2.0.RELEASE.jar:5.2.0.RELEASE]    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.2.0.RELEASE.jar:5.2.0.RELEASE]爪哇春天弹簧靴Spring MVC团结的
查看完整描述

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());

    }

我希望它有帮助。


查看完整回答
反对 回复 2023-12-21
  • 1 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信