RestTemplate获取HTTP状态码
背景
- 使用RestTemplate请求特定接口,并根据获取的HTTP状态码进行具体业务操作。
@RestController
public class RestfulController {private RestTemplate restTemplate = new RestTemplate();@GetMapping("/test1")public void test1(HttpServletResponse response) {response.setStatus(403);}@GetMapping("/test2")public void test2() {ResponseEntity responseEntity = restTemplate.exchange("http://127.0.0.1:8080/test1", HttpMethod.GET, new HttpEntity<String>(null, new HttpHeaders()), String.class);int code = responseEntity.getStatusCodeValue();// 具体业务操作...}
}
报错
org.springframework.web.client.HttpClientErrorException$Forbidden: 403 null
解决
- 如果想要使用responseEntity.getStatusCodeValue()等,需要先为RestTemplate对象设置ResponseErrorHandler。
- 需要注意代码并不符合平常的开发规范,只是为了实现效果。
@RestController
public class RestfulController {private RestTemplate restTemplate = new RestTemplate();@GetMapping("/test1")public void test1(HttpServletResponse response) {response.setStatus(403);}@GetMapping("/test2")public void test2() {restTemplate.setErrorHandler(new RestfulController.ErrorHandler());ResponseEntity responseEntity = restTemplate.exchange("http://127.0.0.1:8080/test1", HttpMethod.GET, new HttpEntity<String>(null, new HttpHeaders()), String.class);int code = responseEntity.getStatusCodeValue();// 业务处理...}static class ErrorHandler implements ResponseErrorHandler {@Overridepublic boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {if (200 == clientHttpResponse.getRawStatusCode()) {return false;}return true;}@Overridepublic void handleError(ClientHttpResponse clientHttpResponse) throws IOException {// 处理Error...}}
}
原因
- RestTemplate
public class RestTemplate extends InterceptingHttpAccessor implements RestOperations {...private ResponseErrorHandler errorHandler;...public RestTemplate() {...// 默认的ResponseErrorHandlerthis.errorHandler = new DefaultResponseErrorHandler();...}...@Nullableprotected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {Assert.notNull(url, "URI is required");Assert.notNull(method, "HttpMethod is required");ClientHttpResponse response = null;Object var14;try {ClientHttpRequest request = this.createRequest(url, method);if (requestCallback != null) {requestCallback.doWithRequest(request);}response = request.execute();// 处理Response, 这里如果抛出异常,就不会返回ResponseEntity对象this.handleResponse(url, method, response);var14 = responseExtractor != null ? responseExtractor.extractData(response) : null;} catch (IOException var12) {String resource = url.toString();String query = url.getRawQuery();resource = query != null ? resource.substring(0, resource.indexOf(63)) : resource;throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + resource + "\": " + var12.getMessage(), var12);} finally {if (response != null) {response.close();}}return var14;}protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {ResponseErrorHandler errorHandler = this.getErrorHandler();boolean hasError = errorHandler.hasError(response);if (this.logger.isDebugEnabled()) {try {int code = response.getRawStatusCode();HttpStatus status = HttpStatus.resolve(code);this.logger.debug("Response " + (status != null ? status : code));} catch (IOException var8) {}}if (hasError) {// 处理Http错误码errorHandler.handleError(url, method, response);}}...
}
- DefaultResponseErrorHandler
public class DefaultResponseErrorHandler implements ResponseErrorHandler {public DefaultResponseErrorHandler() {}public boolean hasError(ClientHttpResponse response) throws IOException {int rawStatusCode = response.getRawStatusCode();HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);return statusCode != null ? this.hasError(statusCode) : this.hasError(rawStatusCode);}protected boolean hasError(HttpStatus statusCode) {return statusCode.isError();}protected boolean hasError(int unknownStatusCode) {Series series = Series.resolve(unknownStatusCode);return series == Series.CLIENT_ERROR || series == Series.SERVER_ERROR;}public void handleError(ClientHttpResponse response) throws IOException {HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());if (statusCode == null) {throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), this.getResponseBody(response), this.getCharset(response));} else {this.handleError(response, statusCode);}}protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {String statusText = response.getStatusText();HttpHeaders headers = response.getHeaders();byte[] body = this.getResponseBody(response);Charset charset = this.getCharset(response);switch(statusCode.series()) {case CLIENT_ERROR:throw HttpClientErrorException.create(statusCode, statusText, headers, body, charset);case SERVER_ERROR:throw HttpServerErrorException.create(statusCode, statusText, headers, body, charset);default:throw new UnknownHttpStatusCodeException(statusCode.value(), statusText, headers, body, charset);}}...
}
- RestTemplate中的getForEntity(…)、 getForObject(…)、exchange(…)和delete(…)等方法最终都是调用doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor responseExtractor)方法。
- 从源代码可以看出来默认的处理器DefaultResponseErrorHandler,最后会抛出三种异常:HttpClientErrorException、HttpServerErrorException、UnknownHttpStatusCodeException。所以在得到ResponseEntity返回值之前,就有异常抛出。
- 可以自定义错误处理器,自定义的处理器并没有抛出异常,所以也就可以返回ResponseEntity对象,并通过该对象的getStatusCodeValue()方法获取HTTP状态码。
RestTemplate获取HTTP状态码相关推荐
- java获取http状态码_java获取Json和http状态码
最近再做接口自动化测试,其中有几个方法比较重要 1.获取http状态码 /** 返回接口状态码 **/ public staticString getHttpCode(String url) { St ...
- 04 Response对象的status_code属性可以获取响应状态码
04 Response对象的status_code属性可以获取响应状态码 文章目录 04 Response对象的status_code属性可以获取响应状态码 4.1 Response.status_c ...
- python模拟点击后获取状态码_Python获取网页状态码
在网页爬取的时候,有时候需要判断下要爬取网页的网页HTTP状态码,然后再进行相关的工作. 1.网页HTTP状态码 HTTP状态码表示HTTP协议所返回的响应状态.具体参考:http://baike.b ...
- js捕获网络请求错误,获取http状态码等信息
js捕获网络请求错误,获取http状态码等信息 第一种:使用$.ajax $(".login").click(function(){$.ajax({type: "POST ...
- Http状态码:简单获取http状态码
简单获取http状态码 Http状态码具体含义 public static void main(String[] args) {try {String str = "https://www. ...
- python requests 状态码_requests获取所有状态码
requests获取所有状态码 requests默认是不会获取301/302的状态码的.可以设置allow_redirects=False,这样就可以获取所有的状态码了 import requests ...
- 前端如何获取http状态码400的返回值
下面小编就为大家带来一篇前端如何获取http状态码400的返回值.小编觉得挺不错的,现在就分享给大家,也给大家做个参考.一起跟随小编过来看看吧 如下所示: 1 2 3 4 5 6 7 8 9 10 1 ...
- 前端获取接口状态码400的返回值
前端获取接口状态码400的返回值 .catch((err) => {console.log(err.message);console.log(err.response.data);console ...
- Golang 获取http状态码
golang语言在提交了get或post请求后,服务器会返回一个请求结果,那么想要获取http响应的状态码就可以使用res.StatusCode来获得一个整型的状态值 package main//获取 ...
- .net使用httpclient获取http状态码_在 .NET Core 中结合 HttpClientFactory 使用 Polly(中篇)...
译者:码农老王 作者:Polly 团队 原文:http://t.cn/EhZ90oq 声明:我翻译技术文章不是逐句翻译的,而是根据我自己的理解来表述的(包括标题).其中可能会去除一些不影响理解但本人实 ...
最新文章
- 编写高效Excel VBA代码的最佳实践(一)
- 软件开发的“三重门”
- pycham窗口显示多个编辑页面
- inDesign入门教程,如何添加阴影效果?
- Django 分页 以及自定义分页
- 时间管理-要抽专门的时间去做那些重要但不紧急的事情
- cf最低要求配置2021是什么
- 计算高德经纬度坐标点之间的距离
- OSChina 周二乱弹 —— 代码中的坑是怎么出现的?
- Tanking个人短网址在线生成源码 个性化设置
- k8s 安装ingress nginx controller 并部署.net core ingress服务
- 如何安装鸿蒙应用,华为鸿蒙OS系统手机怎么安装第三方的应用程序?
- CreateJS入门 -- 注释详细到爆炸(My Style)
- 12. tie_breaker的使用原因和使用方法
- NFT自由人数字艺术藏品有收藏价值吗?
- 德国金融监管机构:ICO急需国际监管
- 基于ncurse的贪吃蛇小游戏
- kali 火路的使用
- linux系统访问bitlocker分区,我将系统盘启用Bitlocker时,系统提示:“系统找不到指定的文件件”...
- 10-ext2 文件系统