可以说RestTemplate更优雅调用RESTful服务的方式,当我们需要远程调用一个HTTP接口时,我们经常会用到RestTemplate这个类。它是一个同步的Rest API客户端,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
RestTemplate使用的包 org.springframework.web.client其实就是对web.client的进一步封装。
一、RestTemplate常用方法
方法大致可以分为三组:
getForObject — optionsForAllow分为一组,这类方法是常规的Rest API(GET、POST、DELETE等)方法调用;
exchange:接收一个RequestEntity 参数,可以自己设置HTTP method, URL, headers和body。返回ResponseEntity。
execute:通过callback 接口,可以对请求和返回做更加全面的自定义控制。
二、使用就是在起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
点进去可以看到spring-web
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.4.RELEASE</version>
<scope>compile</scope>
</dependency>
所以如果在非spring的框架下直接引入spring-web这个包即可
三、RestTemplate原理
建议看这篇文章:
https://blog.csdn.net/lblblblblzdx/article/details/82919235
1对于RestTemplate的拦截器需要注意上面这段代码中的RestTemplate拦截器的处理动作,我们自定义的RestTemplate拦截器就是在这个过程中发挥作用的。我们来看下ClientHttpRequestInterceptor的源码:
@FunctionalInterface
public interface ClientHttpRequestInterceptor {
/**
* Intercept the given request, and return a response. The given
* {@link ClientHttpRequestExecution} allows the interceptor to pass on the
* request and response to the next entity in the chain.
* <p>A typical implementation of this method would follow the following pattern:
* <ol>
* <li>Examine the {@linkplain HttpRequest request} and body</li>
* <li>Optionally {@linkplain org.springframework.http.client.support.HttpRequestWrapper
* wrap} the request to filter HTTP attributes.</li>
* <li>Optionally modify the body of the request.</li>
* <li><strong>Either</strong>
* <ul>
* <li>execute the request using
* {@link ClientHttpRequestExecution#execute(org.springframework.http.HttpRequest, byte[])},</li>
* <strong>or</strong>
* <li>do not execute the request to block the execution altogether.</li>
* </ul>
* <li>Optionally wrap the response to filter HTTP attributes.</li>
* </ol>
* @param request the request, containing method, URI, and headers
* @param body the body of the request
* @param execution the request execution
* @return the response
* @throws IOException in case of I/O errors
*/
ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException;
这里拦截了请求,并实现。详细信息参看
https://blog.csdn.net/YCJ_xiyang/article/details/90673178?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.channel_param
在SpringColud中使用
https://www.cnblogs.com/myitnews/p/12296939.html
别人的配置
https://github.com/rhettpang/RestTemplateSample