参考:https://blog.csdn.net/u011974797/article/details/82424004

https://www.cnblogs.com/liumz0323/p/10633785.html

问题描述:后台用Resttemplate请求失败的话只会在后台报错400,不会返回json错误原因
解决方法:使用HttpClientErrorException异常捕捉

try {
// resttemplate call api
} catch (HttpClientErrorException e) {
//捕捉HTTP异常
e.getResponseBodyAsString();
} catch (Exception e) {
//捕捉所有异常
e.printStackTrace();
}

描述:使用RestTemplate请求url,由于Token等验证信息参数失效,报出 401 HttpClientErrorException异常。
并且获取不到body消息体的错误信息。然而postman工具,是可以返回错误信息的。

原因:RestTemplate 有自己的默认错误处理。在默认的处理里,判断接收到401状态码则抛出
HttpClientErrorException异常,并执行了response.getBody(),这就导致我们后续获取不到body消息体了。

  全局异常处理

@ControllerAdvice
public class ExceptionHandlerController { @ExceptionHandler(HttpClientErrorException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void HttpClientErrorExceptionHandler(HttpClientErrorException ex, HttpServletResponse res) {
UtilFunctions.log.error("HttpClientErrorExceptionHandler, msg: {}, exception: {}", ex.toString(), ex);
UtilFunctions.reportError("HttpClientErrorExceptionHandler: " + ex.toString(), ex, null);
JSONObject response = new JSONObject();
response.put("message", ex.getResponseBodyAsString());
res.setContentType("application/json;charset=utf-8");
try {
res.getWriter().append(response.toString());
} catch (IOException e) {
UtilFunctions.log.error("IOException, exception: {}", e.getMessage(), e);
}
}
}
/*
* 因为Content-Type=application/x-www-form-urlencoded, 所以post请求body中的参数格式也是 a=xxx&b=xxx;
* params可以为null
*
*/
private static HttpEntity<String> requestEntityRequireAuth(HttpServletRequest request, String params) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", getAuthorization(request));
requestHeaders.add("accept", "*/*");
requestHeaders.add("connection", "Keep-Alive");
requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
requestHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
HttpEntity<String> requestEntity = new HttpEntity<String>(params, requestHeaders);
return requestEntity;
} private static HttpEntity<String> requestEntityNotRequireAuth(HttpServletRequest request, String params) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("accept", "*/*");
requestHeaders.add("connection", "Keep-Alive");
requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
requestHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
HttpEntity<String> requestEntity = new HttpEntity<String>(params, requestHeaders);
return requestEntity;
} private static JSONObject returnResult(ResponseEntity<Object> result, HttpServletResponse response) {
int status = result.getStatusCodeValue();
JSONObject obj = new JSONObject();
if (status == 200) {
obj.put("data", result.getBody());
} else {
response.setStatus(status);
obj.put("message", result.getBody());
} return obj;
} private static JSONObject exceptionReturnResult(HttpClientErrorException e, HttpServletResponse response) {
int statusCode = e.getStatusCode().value();
JSONObject obj = new JSONObject();
response.setStatus(statusCode);
obj.put("message", e.getResponseBodyAsString());
return obj;
} /**
* GET请求,需要认证,返回结果中data为JSONObject
*/
public static Object getForObjectRequireAuth(HttpServletRequest request, HttpServletResponse response, String uri) throws Exception {
// 通过ContextProvider从spring容器获取RestTemplate实例
RestTemplate restTemplate = ContextProvider.getBean(RestTemplate.class);
ResponseEntity<Object> result = null;
try {
result = restTemplate.exchange(Config.BASE_SITE + uri, HttpMethod.GET, requestEntityRequireAuth(request, null), Object.class);
} catch (HttpClientErrorException e) {
return exceptionReturnResult(e, response);
}
return returnResult(result, response);
}

Resttemplate请求失败如何获取返回的json的更多相关文章

  1. C# HttpWebRequest请求远程地址获取返回消息

    HttpWebRequest请求远程地址获取返回消息 /// <summary> /// 请求远程Api获取响应返回字符串 /// </summary> /// <par ...

  2. phpStudy4——前端页面使用Ajax请求并解析php返回的json数据

    项目需求: 在html页面显示所有用户列表信息. 需求分析: 1. html页面使用ajax向后端php请求用户数据 2. php脚本查询数据库,并将查询后的结果以json格式返回前端html页面 3 ...

  3. 解决在 使用 AjaxFileUploder 插件时,不能获取返回的 json 结果数据

    在MVC  项目 中使用 AjaxFileUploader 这个插件时,在上传图片或文件时,在控制器中返回的是 json数据,可是在 ie,或 googleChrome 浏览器中却出现 返回的json ...

  4. ExtJS中form提交之后获取返回的json值

    simpleForm.form.doAction('submit', { url : 'editUserType', method : 'post', params : '', // 提交成功后执行s ...

  5. Ajax在静态页面中向指定url发送json请求获取返回的json数据

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  6. URL跨项目调用方法,获取返回的json值,并解析

    package com.mshc.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...

  7. c# 通过URl 获取返回的json格式数据

    方法一 http://blog.csdn.net/angle_greensky110/article/details/52209497 protected string GetJson(string ...

  8. webService 发送soap请求,并解析返回的soap报文

    本例应用场景:要做一个webService测试功能,不局限于任何一种固定格式的webService,所以像axis,cxf等框架就不好用了.只有深入到webService的原理,通过发收soap报文, ...

  9. uploadify ,前端页面获取值,json,ajax

    针对这几月的技术,做一次小总结 上传控件uploadify function inexel() { $("#btnExcel").uploadify({ 'method': 'po ...

随机推荐

  1. [转帖]etcd 在超大规模数据场景下的性能优化

    etcd 在超大规模数据场景下的性能优化   阿里系统软件技术 2019-05-27 09:13:17 本文共5419个字,预计阅读需要14分钟. http://www.itpub.net/2019/ ...

  2. # 数字签名&数字证书

    目录 数字签名&数字证书 数字签名 数字证书 数字证书的实例(https协议) 数字签名&数字证书 参考资料: 数字签名是什么?-阮一峰的网络日志 数字签名和数字证书究竟是什么?知乎- ...

  3. AC自动机练习题1:地图匹配

    AC自动机板子,学习之前要是忘记了就看一下 1465: [AC自动机]地图匹配 poj1204 时间限制: 1 Sec  内存限制: 256 MB提交: 78  解决: 46[提交] [状态] [讨论 ...

  4. js跳转页面的方法

    js跳转页面的几种方法 第一种:(跳转到b.html) <script language="javascript" type="text/javascript&qu ...

  5. 109、Secret的使用场景 (Swarm16)

    参考https://www.cnblogs.com/CloudMan6/p/8082429.html   我们可以用secret管理任何敏感数据.这些敏感数据是容器在运行时需要的.同时我们又不想把这些 ...

  6. 最简单的方式实现rem布局

    加上如下js,px转换成rem需要手动,计算方式:量的大小除以100,就等于rem,例如:量的设计稿元素宽度是120,那么就写成{width: 1.2rem},这样写有什么问题,待研究,也欢迎补充 & ...

  7. vue中添加与删除,关键字搜索

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. ccs之经典布局(二)(两栏,三栏布局)

    接上篇ccs之经典布局(一)(水平垂直居中) 四.两列布局 单列宽度固定,另一列宽度是自适应. 1.float+overflow:auto; 固定端用float进行浮动,自适应的用overflow:a ...

  9. ubuntu 创建定时备份pg数据库定时任务

    ubuntu创建定时备份数据库定时任务 一.命令文件 创建db_back.sh #!/bin/bash echo "start backup" /usr/lib/postgresq ...

  10. 转载:开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别

    转自:https://www.cnblogs.com/findumars/p/6309048.html 首先借用有心人士的一张相当直观清晰的图来划分各种协议:开源许可证GPL.BSD.MIT.Mozi ...