RestTemplate 401 获取错误信息的处理方案
作者:xyw10000 发布时间:2023-01-14 10:37:44
标签:RestTemplate,401
RestTemplate 401错误
调用第三方api 若是服务返回状态码不为200,默认会执行DefaultResponseErrorHandler
异常处理
@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 + "]");
}
}
判断是否异常
protected boolean hasError(HttpStatus statusCode) {
return (statusCode.series() == HttpStatus.Series.CLIENT_ERROR ||
statusCode.series() == HttpStatus.Series.SERVER_ERROR);
}
通常会直接已异常形势抛出,若不特殊处理无法获取返回提示信息。
需要捕捉HttpClientErrorException 异常,则可获取返回信息
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为空讨论
代码复现
实体类
@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);
}
返回结果截图:
返回结果为空的讨论:返回的C类是jpa封装后的类,即使通过json工具,也无法转换成功
解决办法一:实体类转成普通类
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


猜你喜欢
- 本文实例为大家分享了android自定义imageview实现圆角图片的具体代码,供大家参考,具体内容如下自定义图片的属性,对图片进行圆角切
- 本文实例讲述了C# SQLite事务操作方法。分享给大家供大家参考,具体如下:在 C#中执行Sqlite数据库事务有两种方式:SQL代码和C
- 本人使用小米手机,打开qq或者微信的时候,某个权限拒绝的话,会提示你开启,点击开启会跳转到app的权限设置界面,当然了,这是国内系统深层定制
- 相信不少喜欢开发的朋友都已经知道微信小程序是个什么物种了,楼主也是从小程序内测期间就开始关注,并且也写过几个已经上线的微信小程序。但是基本上
- 1.MapView ,MapActivity 这种的局限在于,必须要继承MapActivity,否则无法使用MapView。纠结就在于此。但
- 一个简单的网格布局activity_main.xml<?xml version="1.0" encoding=&q
- 手头项目需要抓取一个用js渲染出来的网站中的数据。使用常用的httpclient抓回来的页面是没有数据。上网百度了一下,大家推荐的方案是使用
- HashMap的keySet()方法比较简单,作用是获取HashMap中的key的集合。虽然这个方法十分简单,似乎没有什么可供分析的,但真正
- 本文实例讲述了java实现文件重命名的方法。分享给大家供大家参考。具体如下:下载的电影总是有一些存在网站名称等没用的信息 作为一个强迫症患者
- Android 实现单线程轮循机制批量下载图片listview 在为item 添加从网上下载下来的图片时, 如果每次都整合一个item时都需
- 本文介绍了JAVA 根据设置的概率生成随机数的方法,分享给大家import java.util.ArrayList;import java.
- 涉及到客户端的系统中经常需要用到比较版本号的功能,但是比较版本号又不能完全按照字符串比较的方式去用compareTo之类的方法;这就需要我们
- 今天启动springboot项目时失败了解决检查原因发现是启动类的MapperScan("")的值写到类名了,改成类所在
- foreach遍历是C#常见的功能,而本文通过实例形式展现了C#使用yield关键字让自定义集合实现foreach遍历的方法。具体步骤如下:
- 目录前言简介在Java上使用创建项目,并引入Jar包导入traineddata编写测试代码训练工具训练数据仓库参考前言Tesseract-O
- 1. openFeign实现基于spring-boot-starter-parent 2.6.8,spring-cloud-dependen
- 本文实例讲述了C#使用HttpDownLoadHelper下载文件的方法。分享给大家供大家参考。具体实现方法如下:using System;
- aes 对称加密密钥必须是32字节using System;using System.Security.Cryptography;using
- 前言之所以要写这篇关于C#反射的随笔,起因有两个:第一个是自己开发的网站需要用到其次就是没看到这方面比较好的文章。所以下定决心自己写一篇,废
- PipedWriter和PipedReader源码分析1. PipedWriter 源码(基于jdk1.7.40) package