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 ... 
随机推荐
- Pandas时间序列和分组聚合
			#时间序列import pandas as pd import numpy as np # 生成一段时间范围 ''' 该函数主要用于生成一个固定频率的时间索引,在调用构造方法时,必须指定start.e ... 
- [python] 进度条效果
			method 1 如果出现多行显示,添加选项 tqdm(iter,ncols=40) """ ncols : int, optional The width of the ... 
- 2019牛客暑期多校训练营(第三场)- F Planting Trees
			题目链接:https://ac.nowcoder.com/acm/contest/883/F 题意:给定n×n的矩阵,求最大子矩阵使得子矩阵中最大值和最小值的差值<=M. 思路:先看数据大小,注 ... 
- git clone 含有子模块的项目
			当一个 git 项目包含子模块(submodule) 时,直接克隆下来的子模块目录里面是空的. 有两种方法解决: 方法一 如果项目已经克隆到了本地,执行下面的步骤: 初始化本地子模块配置文件 git ... 
- Memcached安装 常用指令
			Memcached 源码安装 # 安装依赖yum install -y gcc gcc-c++ automake autoconf make cmake libevent-devel.x86_64# ... 
- 从入门到自闭之Python内置函数
			内置函数一 eval:执行字符串类型的代码 exac:执行字符串社类型的代码 eval与exac 禁止使用 hash()作用就是区分可变数据类型与不可变数据类型 # print(hash(" ... 
- 纯CSS3绘制神奇宝贝伊布动画特效
			在线演示 本地下载 
- 数据绑定-POJO对象绑定参数
			测试: 效果: 
- 多线程编程-- part5.1 互斥锁之公平锁-释放锁
			释放公平锁 1.unlock() unlock()在ReentrantLock.java中实现的,源码如下: public void unlock() { sync.release(1); } 说明: ... 
- 17、Nginx HTTPS 实践
			1.HTTPS安全证书基本概述 为什么需要使用HTTPS, 因为HTTP不安全.当我们使用http网站时,会遭到劫持和篡改,如果采用https协议,那么数据在传输过程中是加密的,所以黑客无法窃取或者篡 ... 
