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 ...
随机推荐
- python 学习jieba库遇到的问题及解决方法
昨天在课堂上学习了jieba库,跟着老师写了同样的代码时却遇到了问题: jieba分词报错AttributeError: module 'jieba' has no attribute 'cut' 文 ...
- 查找担保圈-step3-获取担保圈路径
USE [test] GO /****** Object: StoredProcedure [dbo].[p01_get_group_path] Script Date: 2019/7/8 14:40 ...
- 解决Eclipse发布到Tomcat丢失依赖jar包的问题
解决Eclipse发布到Tomcat丢失依赖jar包的问题 如果jar文件是以外部依赖的形式导入的.Eclipse将web项目发布到Tomcat时,是不会自动发布这些依赖的. 可以通过Eclipse在 ...
- # jsp及servlet学习笔记
目录 jsp及servlet学习笔记 JSP(Java Server Page Java服务端网页) 指令和动作: servlet(小服务程序) jsp及servlet学习笔记 JSP(Java Se ...
- CVE-2018-18955漏洞学习
简介 这是名称空间的漏洞,文章先介绍user namespaces的简单只是,然后从补丁入手,分析源码,找到漏洞出现的原因.因为对这块的源码不是那么熟悉,所以着重描述源码分析的部分,其他可以参考末尾的 ...
- php7.2.1 安装
yum -y install wget openssl* gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype ...
- 通过PlayBook部署Zabbix
编写Linux初始化剧本 初始化剧本环节,主要用户实现关闭Selinux关闭防火墙,一起配置一下阿里云的YUM源地址,和安装EPEL源,为后期的zabbix安装做好铺垫工作. 1.在安装Zabbix之 ...
- TensorFlow入门——hello
上一节说了TensorFlow的安装,这一节说一下测试的问题 新建一个Python文件,输入 import tensorflow as tf hello = tf .constant (’Hello, ...
- CentOS7 SVN基本配置
开机自启指令如下 systemctl enable svnserve.service 对应可执行脚本文件路径 vim /etc/sysconfig/svnserve 查看状态: ps -ef|grep ...
- idea安装完成后要做的几件事(设置字体、编码、行号)
1.设置字体大小和样式 打开设置:File-->Settings 看到如下界面,输入font,点击Editor目录下的Font设置字体大小和样式: Font:字体样式 size:字体大小 Fal ...