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

 更新时间:2021年08月19日 11:07:20   作者:xyw10000  
这篇文章主要介绍了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

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

相关文章

  • idea搭建ssh框架的超详细教程

    idea搭建ssh框架的超详细教程

    这篇文章主要介绍了idea搭建ssh框架的超详细教程,本文通过图文实例代码相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • @ConfigurationProperties加载外部配置方式

    @ConfigurationProperties加载外部配置方式

    这篇文章主要介绍了@ConfigurationProperties加载外部配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • SpringBoot实现埋点监控

    SpringBoot实现埋点监控

    本文主要介绍了SpringBoot实现埋点监控,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • SpringBoot集成Nacos实现注册中心与配置中心流程详解

    SpringBoot集成Nacos实现注册中心与配置中心流程详解

    这篇文章主要介绍了SpringBoot集成Nacos实现注册中心与配置中心流程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-02-02
  • springMVC如何将controller中数据传递到jsp页面

    springMVC如何将controller中数据传递到jsp页面

    这篇文章主要介绍了springMVC如何将controller中数据传递到jsp页面,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • java 线程的生命周期详解

    java 线程的生命周期详解

    这篇文章主要介绍了java 线程的生命周期详解的相关资料,需要的朋友可以参考下
    2017-07-07
  • Java基于中介者模式实现多人聊天室功能示例

    Java基于中介者模式实现多人聊天室功能示例

    这篇文章主要介绍了Java基于中介者模式实现多人聊天室功能,详细分析了中介者模式的概念、原理以及使用中介模式实现多人聊天的步骤、操作技巧与注意事项,需要的朋友可以参考下
    2018-05-05
  • Java中WeakHashMap的使用详解

    Java中WeakHashMap的使用详解

    这篇文章主要介绍了Java中WeakHashMap的使用详解,WeakHashMap是一种弱引用的Map,底层数据结构为数组链表,与HashMap相比,WeakHashMap的区别在于它的key存储为弱引用,在垃圾回收时,如果key没有被强引用所引用,那么key会被回收掉,需要的朋友可以参考下
    2023-09-09
  • 通过JDK源码分析关闭钩子详解

    通过JDK源码分析关闭钩子详解

    一个简单的关闭钩子,程序被中断或者正常退出时会显示 hook shutdown!非常的优雅,有效,巧妙。那么这篇文章就来给大家介绍关于通过JDK源码分析关闭钩子的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴。
    2017-11-11
  • idea64.exe.vmoptions文件如何设置调整VM配置文件

    idea64.exe.vmoptions文件如何设置调整VM配置文件

    这篇文章主要介绍了idea64.exe.vmoptions文件如何设置调整VM配置文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04

最新评论