java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot的RestTemplate

springboot中的RestTemplate使用详解

作者:morris131

这篇文章主要介绍了springboot中的RestTemplate使用详解,RestTemplate继承自InterceptingHttpAccessor并且实现了RestOperations接口,其中RestOperations接口定义了基本的RESTful操作,这些操作在RestTemplate中都得到了实现,需要的朋友可以参考下

RestTemplate介绍

RestTemplate提供了一个基于Http客户端库(HttpClient,OkHttp等)的高层次API,并不是重复制造轮子。

RestTemplate提供了常见的REST请求方案的模版,例如GET请求、POST请求、PUT请求、DELETE请求以及一些通用的请求执行方法exchange以及execute。

RestTemplate已处于维护状态,官方推荐使用WebClient。

RestTemplate继承自InterceptingHttpAccessor并且实现了RestOperations接口,其中RestOperations接口定义了基本的RESTful操作,这些操作在RestTemplate中都得到了实现。

RestTemplate的核心API

RestTemplate的创建

RestTemplate底层默认使用JDK自带的HttpURLConnection来处理请求的。我们可以使用其他HTTP客户端库来处理请求,只需要实现ClientHttpRequestFactory。

目前官方支持的HTTP客户端库有:

例如使用Apache HttpComponents,可以这样创建RestTemplate:

RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

URIs

Restful风格的请求URL上面通常会带有变量。

RestTemplate可以使用可变数组来处理URL上面的变量:

String result = restTemplate.getForObject(
		"https://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");

也可以使用MAP来处理URL上面的变量,MAP中的key需要与URL中的占位符的变量一致:

Map<String, String> vars = Collections.singletonMap("hotel", "42");
String result = restTemplate.getForObject(
		"https://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);

注意URI会自动进行编码,例如:

restTemplate.getForObject("https://example.com/hotel list", String.class);
// Results in request to "https://example.com/hotel%20list"

可以指定RestTemplate的uriTemplateHandler属性来自定义URI如何进行编码,另外RestTemplate的方法也支持传入URI类型的参数。

RestTemplate的简单使用

GET

发送简单的GET请求,URL支持带参数。

@GetMapping("get")
public String getUser() {
    String url = "http://localhost:8888/rest/user/{id}";
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(url, String.class, 1);
    log.info("getForObject: {}", result);
    HashMap<String, Long> map = new HashMap<>();
    map.put("id", 1L);
    String result2 = restTemplate.getForObject(url, String.class, map);
    log.info("getForObject2: {}", result2);
    URI uri = UriComponentsBuilder.fromUriString(url).build(1);
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
    log.info("getForEntity status: {}", responseEntity.getStatusCode());
    log.info("getForEntity header: {}", responseEntity.getHeaders());
    log.info("getForEntity body: {}", responseEntity.getBody());
    return result;
}

POST

发送POST请求。

@GetMapping("post")
public R<Void> postUser() {
    String url = "http://localhost:8888/rest/user";
    RestTemplate restTemplate = new RestTemplate();
    User user = new User();
    user.setName("jj");
    user.setAge(16);
    String result = restTemplate.postForObject(url, user, String.class);
    log.info("postForObject: {}", result);
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
    log.info("postForEntity: {}", responseEntity);
    return R.ok();
}

PUT

发送PUT请求。

@GetMapping("put")
public R<Void> putUser() {
    String url = "http://localhost:8888/rest/user";
    RestTemplate restTemplate = new RestTemplate();
    User user = new User();
    user.setName("jj");
    user.setAge(16);
    restTemplate.put(url, user);
    log.info("put: {}", user);
    return R.ok();
}

DELETE

发送DELETE请求

@GetMapping("delete")
public R<Void> deleteUser() {
    String url = "http://localhost:8888/rest/user/{id}";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.delete(url, 1);
    return R.ok();
}

指定Header

可以使用HttpEntity来指定请求Header头中的参数,也可以使用RequestEntity,RequestEntity是HttpEntity的子类。

可以从ResponseEntity中获取响应的Header头中的参数。

@GetMapping("header")
public R<Void> header() {
    String url = "http://localhost:8888/rest/user";
    RestTemplate restTemplate = new RestTemplate();
    User user = new User();
    user.setName("jj");
    user.setAge(16);
    MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
    paramMap.add("token", "2yy01x90x2xxx25");
    // set headers
    HttpHeaders headers = new HttpHeaders();
    HttpEntity<User> httpEntity = new HttpEntity<>(user, headers);
    ResponseEntity<String> response2 = restTemplate.postForEntity(url, httpEntity, String.class);
    log.info("postForEntity: {}", response2.getBody());
    // 使用exchange请求接口
    ResponseEntity<String> response3 = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
    log.info("exchange: {}", response3.getBody());
    return R.ok();
}

返回值支持泛型

可以使用ParameterizedTypeReference来支持泛型。

@GetMapping("generic")
public R<User> generic() {
    String url = "http://localhost:8888/rest/user/{id}";
    ParameterizedTypeReference<R<User>> parameterizedTypeReference = new ParameterizedTypeReference<R<User>>() {
    };
    RestTemplate template = new RestTemplate();
    ResponseEntity<R<User>> responseEntity = template.exchange(url, HttpMethod.GET, null, parameterizedTypeReference, 1);
    return responseEntity.getBody();
}

消息内容的转换

RestTemplate的方法中能够直接传入对象或者返回对象,这是因为底层使用了HttpMessageConverter进行了转换。

常用的HttpMessageConverter有以下几个:

如果想修改MappingJackson2HttpMessageConverter的序列化或者反序列化方式,可以自定义ObjectMapper来实现:

RestTemplate template = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
template.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter(objectMapper)));

异常处理

RestTemplate发起请求时如果发生错误默认就会直接抛出异常,而不会往下执行,所以无法在代码中直接根据ResponseEntity的status来判断接口是否响应成功,例如下面的代码就会直接抛出异常:

@GetMapping("exception")
public String exception() {
    String url = "http://localhost:8888/rest/user11";
    RestTemplate template = new RestTemplate();
    ResponseEntity<String> responseEntity = template.getForEntity(url, String.class);
    log.info("responseEntity status: {}", responseEntity.getStatusCode());
    return responseEntity.getBody();
}

运行结果如下:

2023-07-19 15:50:49.425 ERROR 15268 --- [nio-8888-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException$NotFound: 404 : "{"timestamp":"2023-07-19T07:50:49.225+00:00","status":404,"error":"Not Found","path":"/rest/user11"}"] with root cause

RestTemplate支持设置ResponseErrorHandler来处理异常,默认是使用DefaultResponseErrorHandler,DefaultResponseErrorHandler的处理就是状态码不是20X都会抛出异常:

protected boolean hasError(int unknownStatusCode) {
    HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
    return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
    if (statusCode == null) {
        byte[] body = getResponseBody(response);
        String message = getErrorMessage(response.getRawStatusCode(),
                response.getStatusText(), body, getCharset(response));
        throw new UnknownHttpStatusCodeException(message,
                response.getRawStatusCode(), response.getStatusText(),
                response.getHeaders(), body, getCharset(response));
    }
    handleError(response, statusCode);
}
private String getErrorMessage(
        int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {
    String preface = rawStatusCode + " " + statusText + ": ";
    if (ObjectUtils.isEmpty(responseBody)) {
        return preface + "[no body]";
    }
    charset = (charset != null ? charset : StandardCharsets.UTF_8);
    String bodyText = new String(responseBody, charset);
    bodyText = LogFormatUtils.formatValue(bodyText, -1, true);
    return preface + bodyText;
}
protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
    String statusText = response.getStatusText();
    HttpHeaders headers = response.getHeaders();
    byte[] body = getResponseBody(response);
    Charset charset = getCharset(response);
    String message = getErrorMessage(statusCode.value(), statusText, body, charset);
    switch (statusCode.series()) {
        case CLIENT_ERROR:
            throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
        case SERVER_ERROR:
            throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
        default:
            throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
    }
}

自定义ResponseErrorHandler进行异常处理:

@GetMapping("exception2")
public R<Void> exception2() {
    String url = "http://localhost:8888/rest/user11";
    RestTemplate template = new RestTemplate();
    template.setErrorHandler(new ResponseErrorHandler() {
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            log.info("hasError: {}", response.getStatusCode());
            return false;
        }
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            // hasError
            log.info("handleError: {}", response.getStatusCode());
        }
    });
    ResponseEntity<String> responseEntity = template.getForEntity(url, String.class);
    log.info("responseEntity status: {}", responseEntity.getStatusCode());
    if(responseEntity.getStatusCode().is2xxSuccessful()) {
        return R.ok();
    }
    return R.fail();
}

拦截请求

RestTemplate支持添加拦截器ClientHttpRequestInterceptor在请求前对请求参数进行处理,在请求后对响应进行处理。

例如可以使用ClientHttpRequestInterceptor对URL进行重写,从注册中心拉取配置实现负载均衡。可以使用ClientHttpRequestInterceptor对Header增加全局TraceId参数,对请求进行链路跟踪定位。

下面通过拦截器来实现负载均衡。

String[] loabancerhost = {"https://www.baidu.com", "https://www.sina.com.cn"};
AtomicInteger times = new AtomicInteger(0);
@GetMapping("intercept")
public String intercept() {
    String url = "http://test";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.singletonList((request, body, execution) -> {
        log.info("请求开始");
        int length = loabancerhost.length;
        int i = times.getAndIncrement() % length;
        // 因为 HttpRequest 和 URI 不提供修改功能,因此需要借助 HttpRequestWrapper 对request进行包装
        Request newRequest = new Request(request, loabancerhost[i]);
        return execution.execute(newRequest, body);
    }));
    ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
    log.info("intercept: {}", exchange);
    return exchange.getBody();
}
private static class Request extends HttpRequestWrapper {
    private String url;
    public Request(HttpRequest request,String url) {
        super(request);
        this.url = url;
    }
    @Override
    public URI getURI() {
        try {
            return new URI(url);
        } catch (URISyntaxException e) {
        }
        return null;
    }
}

到此这篇关于springboot中的RestTemplate使用详解的文章就介绍到这了,更多相关springboot的RestTemplate内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文