服务器之家

服务器之家 > 正文

RestTemplate 401 获取错误信息的处理方案

时间:2021-11-24 13:20     来源/作者:xyw10000

RestTemplate 401错误

调用第三方api 若是服务返回状态码不为200,默认会执行DefaultResponseErrorHandler

异常处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
 public void handleError(ClientHttpResponse response) throws IOException {
  HttpStatus statusCode = getHttpStatusCode(response);
  switch (statusCode.series()) {
   case CLIENT_ERROR:
    throw new HttpClientErrorException(statusCode, response.getStatusText(),
      response.getHeaders(), getResponseBody(response), getCharset(response));
   case SERVER_ERROR:
    throw new HttpServerErrorException(statusCode, response.getStatusText(),
      response.getHeaders(), getResponseBody(response), getCharset(response));
   default:
    throw new RestClientException("Unknown status code [" + statusCode + "]");
  }
 }

判断是否异常

?
1
2
3
4
protected boolean hasError(HttpStatus statusCode) {
 return (statusCode.series() == HttpStatus.Series.CLIENT_ERROR ||
   statusCode.series() == HttpStatus.Series.SERVER_ERROR);
}

通常会直接已异常形势抛出,若不特殊处理无法获取返回提示信息。

需要捕捉HttpClientErrorException 异常,则可获取返回信息

?
1
2
3
4
5
6
7
try{
      ......
    }catch (HttpClientErrorException e) {
                String resBody = e.getResponseBodyAsString();
                log.info("客户端异常返回:{}", resBody);
                return new ResponseEntity<>(JSON.parseObject(resBody, res), e.getStatusCode());
            }

一开始我这样写,死活返回的都是null

原来跟我设置的requestFactory有关

采用SimpleClientHttpRequestFactory 无法获取提示

需要换成 HttpComponentsClientHttpRequestFactory

RestTemplate通过对象传参,response的body为空讨论

代码复现

实体类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Entity
@Table(name = "a",schema = "a")
@JsonIgnoreProperties(value = {"a"})
@Setter
@Generated
public class C {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name = "diseaseName",length = 255,nullable = false,unique = true)
    private String diseaseName;
    @Column(name = "description",length = 255,nullable = false,unique = true)
    private String description;
    @Column(name = "department",length = 255,nullable = false,unique = true)
    private String department;
}
controller
@ResponseBody
    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response APIcreate(@RequestBody C c) {
        String json = JSONUtil.toJSONString(c);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        String url = "http://localhost:3001/c";
        ResponseEntity<Commondisease> responseEntity = restTemplate.postForEntity(url, entity, C.class);
        return new ResponseData(ExceptionMsg.SUCCESS, responseEntity);
    }

返回结果截图:

RestTemplate 401 获取错误信息的处理方案

返回结果为空的讨论:返回的C类是jpa封装后的类,即使通过json工具,也无法转换成功

解决办法一:实体类转成普通类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class C {
    private Integer id;
    private String diseaseName;
    private String description;
    private String department;
}
 @ResponseBody
    @RequestMapping(value = "",method = RequestMethod.POST)
    public Response APIcreate(@RequestBody C c) {
        //C c = new Commondisease(1,"zhangsan","11","2222");
        String json = JSONUtil.toJSONString(c);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        String url = "http://localhost:3001/c/";
        ResponseEntity<Commondisease> responseEntity =         restTemplate.postForEntity(url,entity,C.class);
        return new ResponseData(ExceptionMsg.SUCCESS,responseEntity);
}

返回成功

解决办法二:添加注解

@Data

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xuyw10000/article/details/88790391

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部