restTemplate解析401异常失败

系列文章目录

第一章 spring框架构成
第二章 spring容器
第三章 spring配置bean
第四章 bean的继承和依赖
第五章 bean的生命周期
第六章 spring依赖注入
第七章 Spring AOP
第八章 spring事务
第九章 spring事件监听
第十章 web应用使用spring
第十一章 spring注解整理
第十二章 spring事务失效场景
第十三章 spring bean的作用域
第十四章 spring的扩展接口
第十五章 spring引入外部属性文件
第十六章 spring自定义属性编辑器
第十七章 spring配置双数据源
第十八章 restTemplate解析401异常失败



restTemplate解析401异常失败

原文链接 https://zhhll.icu/2020/框架/spring/restTemplate/restTemplate解析401异常失败/

如果使用restTemplate默认构造器的话,在进行错误解析的时候,使用

if (response.getStatusCode().isError()) { // 4XX或者5XX
		InputStream inputStream = response.getBody();
}

// 此时这个response是SimpleClientHttpResponse
// 此方法为SimpleClientHttpResponse的getBody()方法
@Override
	public InputStream getBody() throws IOException {
        // 在这一行取出的errorStream是null  这个connection使用的是private final HttpURLConnection connection;
		InputStream errorStream = this.connection.getErrorStream();
		this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
		return this.responseStream;
}

这时候需要在创建restTemplate的时候更改requestFactory,使用HttpComponentsClientHttpRequestFactory

RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
posted @   拾光师  阅读(13)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示