RestTemplate的配置和使用

た 入场券 2024-01-01 06:43 108阅读 0赞

配置

  1. /**
  2. * resttemplate 配置
  3. */
  4. @Configuration
  5. public class RestTemplateConfig {
  6. @Bean
  7. public SimpleClientHttpRequestFactory simpleClientHttpRequestFactory() {
  8. SimpleClientHttpRequestFactory facotry = new SimpleClientHttpRequestFactory();
  9. /*10s*/
  10. facotry.setReadTimeout(10000);
  11. /*30s*/
  12. facotry.setConnectTimeout(30000);
  13. return facotry;
  14. }
  15. @Bean(name = "restTemplate")
  16. public RestTemplate restTemplate(SimpleClientHttpRequestFactory factory) {
  17. RestTemplate restTemplate = new RestTemplate(factory);
  18. restTemplate.setErrorHandler(new RestTemplateErrorHandler());
  19. return restTemplate;
  20. }
  21. }

配置异常处理

  1. /**
  2. * 定义处理resttemplate的异常
  3. */
  4. public class RestTemplateErrorHandler implements ResponseErrorHandler {
  5. @Override
  6. public boolean hasError(ClientHttpResponse response) throws IOException {
  7. boolean hasError = false;
  8. int rawStatusCode = response.getRawStatusCode();
  9. if (rawStatusCode != 200){
  10. hasError = true;
  11. }
  12. return hasError;
  13. }
  14. @Override
  15. public void handleError(ClientHttpResponse response) throws IOException {
  16. String body = IOUtils.toString(response.getBody(), "UTF-8");
  17. String msg = null;
  18. if(StringUtils.isNotEmpty(body)) {
  19. JSONObject jsonObj = JSON.parseObject(body);
  20. Object msgObj = jsonObj.get("errMsg");
  21. if(msgObj == null) {
  22. msg = body;
  23. } else {
  24. msg = msgObj.toString();
  25. }
  26. }
  27. RestCustomException ex = new RestCustomException(response.getStatusCode(), body, (msg == null ? "" : msg));
  28. throw ex;
  29. }
  30. }

抛出异常配置

  1. public class RestCustomException extends RuntimeException {
  2. private static final long serialVersionUID = 1L;
  3. private HttpStatus statusCode;
  4. private String body;
  5. public RestCustomException(String msg) {
  6. super(msg);
  7. }
  8. public RestCustomException(HttpStatus statusCode, String body, String msg) {
  9. super(msg);
  10. this.statusCode = statusCode;
  11. this.body = body;
  12. }
  13. public HttpStatus getStatusCode() {
  14. return statusCode;
  15. }
  16. public void setStatusCode(HttpStatus statusCode) {
  17. this.statusCode = statusCode;
  18. }
  19. public String getBody() {
  20. return body;
  21. }
  22. public void setBody(String body) {
  23. this.body = body;
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,108人围观)

还没有评论,来说两句吧...

相关阅读

    相关 restTemplate使用

    目录 目录 一、概述? 二、使用步骤 1.引入依赖 2.创建RestTemplate对象,交由spring容器进行管理 3.使用方法 3.1 GET请求