RestTemplate接口请求发送json、form数据格式以及处理接口错误状态码400 null

您所在的位置:网站首页 数据接口参数 RestTemplate接口请求发送json、form数据格式以及处理接口错误状态码400 null

RestTemplate接口请求发送json、form数据格式以及处理接口错误状态码400 null

2024-06-12 16:16| 来源: 网络整理| 查看: 265

前言

  在日常的开发过程当中,难免我们会经常几个服务穿插起来一起开发,各个服务相互请求,这个时候就涉及到网络请求过程,Spring就提供了一个非常便捷的请求方式:RestTemplate 。   以下以post请求为例,分别展示,form、json格式进行传参

构造RestTemplate实例

构造该实例,一共以下有两种方法。需要注意的是通过注入的形式该RestTemplate是单例的

// 第一种方法 @Resource private RestTemplate restTemplate; // 第二种方法 RestTemplate restTemplate = new RestTemplate(); JSON 数据格式 处理参数 Map requestData = new HashMap(); requestData.add("xxx", xxx); requestData.add("xxx", xxx); ... 设置请求内容 /** * 生成post请求的JSON请求参数 包含请求头等信息 * * @param map 需要发送的json数据 * @return 设置请求头 */ private HttpEntity generatePostJson(Map map) { // 1. 设置请求头 HttpHeaders httpHeaders = new HttpHeaders(); MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE); httpHeaders.setContentType(type); // 2. 设置请求数据 return new HttpEntity(map, httpHeaders); } 开始发送,拿到成功之后的响应内容 HttpEntity httpEntity = generatePostJson(map); ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, String.class); 根据自己需求对响应内容进行拆解 JSONObject result = JSONObject.parseObject(responseEntity.getBody()); HttpStatus status = responseEntity.getStatusCode(); FORM数据格式 处理参数 MultiValueMap requestData = new LinkedMultiValueMap(); requestData.add("xxx", xxx); requestData.add("xxx", xxx); 。。。 设置请求内容 /** * 生成post请求的form请求参数 包含请求头等信息 * * @param map 需要发送的form数据 * @return 设置请求头 */ private HttpEntity generatePostForm(MultiValueMap map) { // 1. 设置请求头 HttpHeaders httpHeaders = new HttpHeaders(); MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_FORM_URLENCODED_VALUE); httpHeaders.setContentType(type); // 2. 设置请求数据 return new HttpEntity(map, httpHeaders); } 开始发送,拿到成功之后的响应内容 HttpEntity httpEntity = generatePostForm(map); ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, String.class); 根据自己需求对响应内容进行拆解 JSONObject result = JSONObject.parseObject(responseEntity.getBody()); HttpStatus status = responseEntity.getStatusCode(); 注意事项

restTemplate.postForEntity(url, httpEntity, String.class); 他是无法返回失败的接口请求的!当接口返回400、500等错误状态码,接受到的所有响应内容全为状态码 null 。

解决方案

自己写处理异常的方法,当出现异常之后,自己将错误信息重新包装。

第一步 // 在请求之前,需要setErrorHandler 将自定义处理错误异常传进去 restTemplate.setErrorHandler(new CustomResponseErrorHandler()); restTemplate.postForEntity(url, httpEntity, String.class); 第二步 CustomResponseErrorHandler.java package com.afd.error; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestClientException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; /** * @author xiaoxi * @version 1.0 * @date 2021/9/9 16:22 */ public class CustomResponseErrorHandler implements ResponseErrorHandler { private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler(); @Override public void handleError(ClientHttpResponse response) throws IOException { // 队请求头的处理 List customHeader = response.getHeaders().get("x-app-err-id"); String svcErrorMessageID = ""; if (customHeader != null) { svcErrorMessageID = customHeader.get(0); } // 对body 的处理 (inputStream) String body = convertStreamToString(response.getBody()); try { errorHandler.handleError(response); } catch (RestClientException scx) { throw new CustomException(scx.getMessage(), scx, body); } } @Override public boolean hasError(ClientHttpResponse response) throws IOException { return errorHandler.hasError(response); } // inputStream 装换为 string private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } CustomException.java package com.afd.error; import org.springframework.web.client.RestClientException; /** * @author xiaoxi * @version 1.0 * @date 2021/9/9 16:23 */ public class CustomException extends RestClientException { private RestClientException restClientException; private String body; public RestClientException getRestClientException() { return restClientException; } public void setRestClientException(RestClientException restClientException) { this.restClientException = restClientException; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public CustomException(String msg, RestClientException restClientException, String body) { super(msg); this.restClientException = restClientException; this.body = body; } } 第三步 // 2. 开始发送 try { restTemplate.setErrorHandler(new CustomResponseErrorHandler()); restTemplate.postForEntity(url, httpEntity, String.class); } catch (CustomException e) { log.info(e.getBody()); throw new ErrorMessageException(e.getBody()); }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3