当前位置:   article > 正文

解决报错:org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]

org.springframework.web.client.httpclienterrorexception$unauthorized: 401 :
文件名称版本号作者qq版本
解决报错:org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]v1.0.0学生宫布8416837SpringBoot 2.2.6
SpringCloud Hoxton.SR4

同时解决:java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode

报错全称

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
后台抛异常,前端页面浏览器显示状态码500,内部错误。是不准确的。
在这里插入图片描述
但事实上是401错误
因后端抛出了异常导致

代码 见解决方案

疑似产生的原因

比如,客户端使用过期的令牌调用后端,后端通过auth-server鉴定为过期令牌,则抛出异常

弯路、坑

分析

不使用spring-web的DefaultResponseErrorHandler.java处理401异常,则会向客户端浏览器响应错误数据

解决方案

改代码↓

	@Bean
    @LoadBalanced
    public RestTemplate restTemplate()
    {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

改为

 	@Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setOutputStreaming(false); // 解决401报错时,报java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new RtErrorHandler());

        return restTemplate;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • RtErrorHandler.java 白名单上的异常则不处理,直接返回
/**
 * 功能:捕获RestTemplate异常
 *
 * @author: cc
 * @qq: 8416837
 * @date: 2020/11/23 18:08
 */
public class RtErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return super.hasError(response);
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
        List<HttpStatus> donotDeal = new ArrayList<>(); // 白名单
        donotDeal.add(HttpStatus.UNAUTHORIZED);

        if (!donotDeal.contains(statusCode)) { // 非白名单则处理
            super.handleError(response);
        }
    }

}
  • 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

这样前端可以获取到restTemplate错误,比如↓
在这里插入图片描述

在这里插入图片描述
这样就比较清晰了,——不合法的令牌

领悟

restTemplate也是HTTPClient,可以有响应

关于

若交流技术,请联系qq:8416837

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号