微服务调用feign接口报错401的解决方案和原因总结

feign.FeignException$Unauthorized: [401 Unauthorized] during [GET] to [[http://xxx/xxx]

报错详情:

feign.FeignException$Unauthorized: [401 Unauthorized] during [GET] to [http://govern-traffic-law/eventAnalysis/evtRatioAnalysis?type=3&streetId=1] [ITrafficEventClassifyFeignClientService#evtRatioAnalysis(String,String)]: [{
    
    "path":"/eventAnalysis/evtRatioAnalysis","data":false,"message":"访问此资源需要身份验证","error":null,"status":401,"timestamp":"2021-05-27 09:58:24"}]
	at feign.FeignException.clientErrorStatus(FeignException.java:197)
	at feign.FeignException.errorStatus(FeignException.java:177)
	at feign.FeignException.errorStatus(FeignException.java:169)
	at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:92)
	at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:156)
	at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:80)
	at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:100)
	at com.sun.proxy.$Proxy129.evtRatioAnalysis(Unknown Source)
	at com.zrx.govern.state.governanceresult.serviceImpl.ComprehensiveLawServiceImpl.getEventNum(ComprehensiveLawServiceImpl.java:36)
	at 

重点看前面几行。401的错误
错误原因:
1、没有传token
我用postman测得时候,已经加了
在这里插入图片描述
2、于是我就找application.yml中得配置,接口得服务也加了
在这里插入图片描述
查找,被调用的服务配置application.yml
在这里插入图片描述
3、设置feign接口的拦截器
在这里插入图片描述
FeignConfig类如下:

@Configuration
public class FeignConfig implements RequestInterceptor {
    
    
    @Override
    public void apply(RequestTemplate template) {
    
    
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //添加token
        template.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
    }
}

我查找了很多大佬的博客,都没找到我的问题的原因,最后,2是我的解决方案。
总结以上原因,供大家参考

猜你喜欢

转载自blog.csdn.net/victo_chao/article/details/117321886