Resttemplate请求失败如何获取返回的json
参考: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的更多相关文章
- C# HttpWebRequest请求远程地址获取返回消息
HttpWebRequest请求远程地址获取返回消息 /// <summary> /// 请求远程Api获取响应返回字符串 /// </summary> /// <par ...
- phpStudy4——前端页面使用Ajax请求并解析php返回的json数据
项目需求: 在html页面显示所有用户列表信息. 需求分析: 1. html页面使用ajax向后端php请求用户数据 2. php脚本查询数据库,并将查询后的结果以json格式返回前端html页面 3 ...
- 解决在 使用 AjaxFileUploder 插件时,不能获取返回的 json 结果数据
在MVC 项目 中使用 AjaxFileUploader 这个插件时,在上传图片或文件时,在控制器中返回的是 json数据,可是在 ie,或 googleChrome 浏览器中却出现 返回的json ...
- ExtJS中form提交之后获取返回的json值
simpleForm.form.doAction('submit', { url : 'editUserType', method : 'post', params : '', // 提交成功后执行s ...
- Ajax在静态页面中向指定url发送json请求获取返回的json数据
<html> <head> <meta http-equiv="Content-Type" content="text/html; char ...
- URL跨项目调用方法,获取返回的json值,并解析
package com.mshc.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...
- c# 通过URl 获取返回的json格式数据
方法一 http://blog.csdn.net/angle_greensky110/article/details/52209497 protected string GetJson(string ...
- webService 发送soap请求,并解析返回的soap报文
本例应用场景:要做一个webService测试功能,不局限于任何一种固定格式的webService,所以像axis,cxf等框架就不好用了.只有深入到webService的原理,通过发收soap报文, ...
- uploadify ,前端页面获取值,json,ajax
针对这几月的技术,做一次小总结 上传控件uploadify function inexel() { $("#btnExcel").uploadify({ 'method': 'po ...
随机推荐
- 第五周课程总结&试验报告三
第五周课程总结 一.第五周课程总结 1.this关键字 this可用于任何实例方法内指向当前对象,也可指向对其调用当前方法的对象,或者在需要当前类型对象引用时使用.当一个类的属性(成员变量)名与访问该 ...
- # Excel批量处理数据
Excel批量处理数据 拖住框下拉即可得到每行+3的结果
- 如何用纯 CSS 创作六边形按钮特效
效果预览 在线演示 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/xjoOeM 可交互视频教 ...
- Postman之获得登录的token,并设置为全局变量
1.调通登录接口(可以参考上篇博客) 网址:Postman之简单使用 2.粘贴以下代码到Tests中 //把json字符串转化为对象 var data=JSON.parse(responseBody) ...
- oa_mvc_easyui_删除(6)
1.删除列,添加a标签,绑定参数 <a href="javascript:void(0)" class="delete" ids="@newli ...
- LaTeX pdf转eps格式
使用GSview对pdf 进行 eps 转换 1.准备好PDF文件 例如:f1.pdf 2.打开GSview,转换f1.pdf成为f1.ps 打开GSview,File-->Convert--& ...
- 安装kubuctl
安装和设置kubectl 使用Kubernetes命令行工具kubectl在Kubernetes上部署和管理应用程序.使用kubectl,可以检查集群资源; 创建,删除和更新组件. 以下是安装kube ...
- O003、准备 KVM 实验环境
参考https://www.cnblogs.com/CloudMan6/p/5240770.html KVM 是 OpenStack 使用的最广泛的Hypervisor,本节介绍如何搭建 KVM ...
- 11 Scrapy框架之递归解析和post请求
一.递归爬取解析多页页面数据 - 需求:将糗事百科所有页码的作者和段子内容数据进行爬取切持久化存储 - 需求分析:每一个页面对应一个url,则scrapy工程需要对每一个页码对应的url依次发起请求, ...
- 第一个简单的Echarts实例
该示例使用 vue-cli 脚手架搭建 安装echarts依赖 npm install echarts -S 或者使用国内的淘宝镜像: 安装 npm install -g cnpm --registr ...