RestTemplate 源码的简单分析
//使用示例 @PostMapping("/judge") public boolean judge() { RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class); return false; }
@Override public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables)); } ... @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException { ... ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); handleResponse(url, method, response); return (responseExtractor != null ? responseExtractor.extractData(response) : null); } catch (IOException ex) { ... } finally { ... } }
到了 HttpAccessor 的 createRequest 方法
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException { ClientHttpRequest request = getRequestFactory().createRequest(url, method); initialize(request); if (logger.isDebugEnabled()) { logger.debug("HTTP " + method.name() + " " + url); } return request; } /** * Return the request factory that this accessor uses for obtaining client request handles. */ public ClientHttpRequestFactory getRequestFactory() { return this.requestFactory; }
而 ClientHttpRequestFactory 是什么。
这张图就可以看出 ClientHttpRequestFactory 的实现有多个,而 RestTemplate则封装了组装、发送 HTTP消息,以及解析响应的底层细节。
spring 很多也进行这样的封装,比如log 。
参考资料
- https://www.baeldung.com/rest-template (template 使用)