RestTemplate使用详解

今天药忘吃喽~ 2022-12-07 11:46 325阅读 0赞

RestTemplate使用详解

RestTemplateSpring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

我之前的HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,稍微截个图,这是我封装好的一个post请求工具:

format_png

本教程将带领大家实现Spring生态内RestTemplate的Get请求Post请求还有exchange指定请求类型的实践和RestTemplate核心方法源码的分析,看完你就会用优雅的方式来发HTTP请求。

1. 简述RestTemplate

Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponentsNettyOkHttp

RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能,但只有理解了HttpEntity的组成结构(header与body),且理解了与uriVariables之间的差异,才能真正掌握其用法。这一点在Post请求更加突出,下面会介绍到。

该类的入口主要是根据HTTP的六个方法制定:


















































HTTP method RestTemplate methods
DELETE delete
GET getForObject
  getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
POST postForLocation
  postForObject
PUT put
any exchange
  execute

此外,exchange和excute可以通用上述方法。

在内部,RestTemplate默认使用HttpMessageConverter实例将HTTP消息转换成POJO或者从POJO转换成HTTP消息。默认情况下会注册主mime类型的转换器,但也可以通过setMessageConverters注册其他的转换器。(其实这点在使用的时候是察觉不到的,很多方法有一个responseType 参数,它让你传入一个响应体所映射成的对象,然后底层用HttpMessageConverter将其做映射)

  1. HttpMessageConverterExtractor<T> responseExtractor =
  2. new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);

HttpMessageConverter.java源码:

  1. public interface HttpMessageConverter<T> {
  2. //指示此转换器是否可以读取给定的类。
  3. boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
  4. //指示此转换器是否可以写给定的类。
  5. boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
  6. //返回List<MediaType>
  7. List<MediaType> getSupportedMediaTypes();
  8. //读取一个inputMessage
  9. T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
  10. throws IOException, HttpMessageNotReadableException;
  11. //往output message写一个Object
  12. void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
  13. throws IOException, HttpMessageNotWritableException;
  14. }

在内部,RestTemplate默认使用SimpleClientHttpRequestFactoryDefaultResponseErrorHandler来分别处理HTTP的创建和错误,但也可以通过setRequestFactorysetErrorHandler来覆盖。

2. get请求实践

2.1. getForObject()方法

  1. public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables){}
  2. public <T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables)
  3. public <T> T getForObject(URI url, Class<T> responseType)

getForObject()其实比getForEntity()多包含了将HTTP转成POJO的功能,但是getForObject没有处理response的能力。因为它拿到手的就是成型的pojo。省略了很多response的信息。

2.1.1 POJO:

  1. public class Notice {
  2. private int status;
  3. private Object msg;
  4. private List<DataBean> data;
  5. }
  6. public class DataBean {
  7. private int noticeId;
  8. private String noticeTitle;
  9. private Object noticeImg;
  10. private long noticeCreateTime;
  11. private long noticeUpdateTime;
  12. private String noticeContent;
  13. }

示例:2.1.2 不带参的get请求

  1. /**
  2. * 不带参的get请求
  3. */
  4. @Test
  5. public void restTemplateGetTest(){
  6. RestTemplate restTemplate = new RestTemplate();
  7. Notice notice = restTemplate.getForObject("http://xxx.top/notice/list/1/5"
  8. , Notice.class);
  9. System.out.println(notice);
  10. }

控制台打印:

  1. INFO 19076 --- [ main] c.w.s.c.w.c.HelloControllerTest
  2. : Started HelloControllerTest in 5.532 seconds (JVM running for 7.233)
  3. Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', noticeImg=null,
  4. noticeCreateTime=1525292723000, noticeUpdateTime=1525292723000, noticeContent='<p>aaa</p>'},
  5. DataBean{noticeId=20, noticeTitle='ahaha', noticeImg=null, noticeCreateTime=1525291492000,
  6. noticeUpdateTime=1525291492000, noticeContent='<p>ah.......'

示例:2.1.3 带参数的get请求1

  1. Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}"
  2. , Notice.class,1,5);

明眼人一眼能看出是用了占位符{1}

示例:2.1.4 带参数的get请求2

  1. Map<String,String> map = new HashMap();
  2. map.put("start","1");
  3. map.put("page","5");
  4. Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/"
  5. , Notice.class,map);

明眼人一看就是利用map装载参数,不过它默认解析的是PathVariable的url形式。

2.2 getForEntity()方法

  1. public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables){}
  2. public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables){}
  3. public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType){}

与getForObject()方法不同的是返回的是ResponseEntity对象,如果需要转换成pojo,还需要json工具类的引入,这个按个人喜好用。不会解析json的可以百度FastJson或者Jackson等工具类。然后我们就研究一下ResponseEntity下面有啥方法。

ResponseEntity、HttpStatus、BodyBuilder结构

ResponseEntity.java

  1. public HttpStatus getStatusCode(){}
  2. public int getStatusCodeValue(){}
  3. public boolean equals(@Nullable Object other) {}
  4. public String toString() {}
  5. public static BodyBuilder status(HttpStatus status) {}
  6. public static BodyBuilder ok() {}
  7. public static <T> ResponseEntity<T> ok(T body) {}
  8. public static BodyBuilder created(URI location) {}
  9. ...

HttpStatus.java

  1. public enum HttpStatus {
  2. public boolean is1xxInformational() {}
  3. public boolean is2xxSuccessful() {}
  4. public boolean is3xxRedirection() {}
  5. public boolean is4xxClientError() {}
  6. public boolean is5xxServerError() {}
  7. public boolean isError() {}
  8. }

BodyBuilder.java

  1. public interface BodyBuilder extends HeadersBuilder<BodyBuilder> {
  2. //设置正文的长度,以字节为单位,由Content-Length标头
  3. BodyBuilder contentLength(long contentLength);
  4. //设置body的MediaType 类型
  5. BodyBuilder contentType(MediaType contentType);
  6. //设置响应实体的主体并返回它。
  7. <T> ResponseEntity<T> body(@Nullable T body);

可以看出来,ResponseEntity包含了HttpStatus和BodyBuilder的这些信息,这更方便我们处理response原生的东西。

示例:

  1. @Test
  2. public void rtGetEntity(){
  3. RestTemplate restTemplate = new RestTemplate();
  4. ResponseEntity<Notice> entity = restTemplate.getForEntity("http://fantj.top/notice/list/1/5"
  5. , Notice.class);
  6. HttpStatus statusCode = entity.getStatusCode();
  7. System.out.println("statusCode.is2xxSuccessful()"+statusCode.is2xxSuccessful());
  8. Notice body = entity.getBody();
  9. System.out.println("entity.getBody()"+body);
  10. ResponseEntity.BodyBuilder status = ResponseEntity.status(statusCode);
  11. status.contentLength(100);
  12. status.body("我在这里添加一句话");
  13. ResponseEntity<Class<Notice>> body1 = status.body(Notice.class);
  14. Class<Notice> body2 = body1.getBody();
  15. System.out.println("body1.toString()"+body1.toString());
  16. }
  17. statusCode.is2xxSuccessful()true
  18. entity.getBody()Notice{status=200, msg=null, data=[DataBean{noticeId=21, noticeTitle='aaa', ...
  19. body1.toString()<200 OK,class com.waylau.spring.cloud.weather.pojo.Notice,{Content-Length=[100]}>

当然,还有getHeaders()等方法没有举例。

3. post请求实践

同样的,post请求也有postForObjectpostForEntity

  1. public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
  2. throws RestClientException {}
  3. public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
  4. throws RestClientException {}
  5. public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {}

示例

我用一个验证邮箱的接口来测试。

  1. @Test
  2. public void rtPostObject(){
  3. RestTemplate restTemplate = new RestTemplate();
  4. String url = "http://47.xxx.xxx.96/register/checkEmail";
  5. HttpHeaders headers = new HttpHeaders();
  6. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  7. MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
  8. map.add("email", "844072586@qq.com");
  9. HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
  10. ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
  11. System.out.println(response.getBody());
  12. }

执行结果:

  1. {"status":500,"msg":"该邮箱已被注册","data":null}

format_png 1

代码中,MultiValueMapMap的一个子类,它的一个key可以存储多个value,简单的看下这个接口:

  1. public interface MultiValueMap<K, V> extends Map<K, List<V>> {...}

为什么用MultiValueMap?因为HttpEntity接受的request类型是它。

  1. public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers){}
  2. 我这里只展示它的一个construct,从它可以看到我们传入的map是请求体,headers是请求头。

为什么用HttpEntity是因为restTemplate.postForEntity方法虽然表面上接收的request是@Nullable Object request类型,但是你追踪下去会发现,这个request是用HttpEntity来解析。核心代码如下:

  1. if (requestBody instanceof HttpEntity) {
  2. this.requestEntity = (HttpEntity<?>) requestBody;
  3. }else if (requestBody != null) {
  4. this.requestEntity = new HttpEntity<>(requestBody);
  5. }else {
  6. this.requestEntity = HttpEntity.EMPTY;
  7. }

我曾尝试用map来传递参数,编译不会报错,但是执行不了,是无效的url request请求(400 ERROR)。其实这样的请求方式已经满足post请求了,cookie也是属于header的一部分。可以按需求设置请求头和请求体。其它方法与之类似。

4. 使用exchange指定调用方式

exchange()方法跟上面的getForObject()、getForEntity()、postForObject()、postForEntity()等方法不同之处在于它可以指定请求的HTTP类型。

format_png 2

但是你会发现exchange的方法中似乎都有@Nullable HttpEntity<?> requestEntity这个参数,这就意味着我们至少要用HttpEntity来传递这个请求体,之前说过源码所以建议就使用HttpEntity提高性能。

示例

  1. @Test
  2. public void rtExchangeTest() throws JSONException {
  3. RestTemplate restTemplate = new RestTemplate();
  4. String url = "http://xxx.top/notice/list";
  5. HttpHeaders headers = new HttpHeaders();
  6. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  7. JSONObject jsonObj = new JSONObject();
  8. jsonObj.put("start",1);
  9. jsonObj.put("page",5);
  10. HttpEntity<String> entity = new HttpEntity<>(jsonObj.toString(), headers);
  11. ResponseEntity<JSONObject> exchange = restTemplate.exchange(url,
  12. HttpMethod.GET, entity, JSONObject.class);
  13. System.out.println(exchange.getBody());
  14. }

这次可以看到,我使用了JSONObject对象传入和返回。

当然,HttpMethod方法还有很多,用法类似。

5. excute()指定调用方式

excute()的用法与exchange()大同小异了,它同样可以指定不同的HttpMethod,不同的是它返回的对象是响应体所映射成的对象<T>,而不是ResponseEntity<T>

需要强调的是,execute()方法是以上所有方法的底层调用。随便看一个:

  1. @Override
  2. @Nullable
  3. public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
  4. throws RestClientException {
  5. RequestCallback requestCallback = httpEntityCallback(request, responseType);
  6. HttpMessageConverterExtractor<T> responseExtractor =
  7. new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger);
  8. return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);
  9. }

在项目中,当我们需要远程调用一个HTTP接口时,我们经常会用到RestTemplate这个类。这个类是Spring框架提供的一个工具类。Spring官网对它的介绍如下:

RestTemplate: The original Spring REST client with a synchronous, template method API.

从上面的介绍中我们可以知道:RestTemplate是一个同步的Rest API客户端。下面我们就来介绍下RestTemplate的常用功能。

RestTemplate简单使用#

RestTemplate提供高度封装的接口,可以让我们非常方便地进行Rest API调用。常见的方法如下:

表格:RestTemplate的方法

format_png 3

上面的方法我们大致可以分为三组:

  • getForObject —- optionsForAllow分为一组,这类方法是常规的Rest API(GET、POST、DELETE等)方法调用;
  • exchange:接收一个RequestEntity 参数,可以自己设置HTTP method, URL, headers和body。返回ResponseEntity。
  • execute:通过callback 接口,可以对请求和返回做更加全面的自定义控制。

一般情况下,我们使用第一组和第二组方法就够了。

创建RestTemplate#

  1. @Bean
  2. public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  3. RestTemplate restTemplate = new RestTemplate(factory);
  4. return restTemplate;
  5. }
  6. @Bean
  7. public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
  8. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  9. factory.setReadTimeout(5000);
  10. factory.setConnectTimeout(15000);
  11. //设置代理
  12. //factory.setProxy(null);
  13. return factory;
  14. }

创建RestTemplate时需要一个ClientHttpRequestFactory,通过这个请求工厂,我们可以统一设置请求的超时时间,设置代理以及一些其他细节。通过上面代码配置后,我们直接在代码中注入RestTemplate就可以使用了。

接口调用#

1. 普通接口调用

  1. Map<String, String> vars = Collections.singletonMap("hotel", "42");
  2. //通过GET方式调用,返回一个String值,还可以给URL变量设置值(也可通过uriTemplateHandler这个属性自定义)
  3. String result = restTemplate.getForObject(
  4. "https://example.com/hotels/{hotel}/rooms/{hotel}", String.class, vars);
  5. String url = "http://127.0.0.1:8080/hello";
  6. JSONObject param = new JSONObject();
  7. //restTemplate会根据params的具体类型,调用合适的HttpMessageConvert将请求参数写到请求体body中,并在请求头中添加合适的content-type;
  8. //也会根据responseType的类型(本列子中是JSONObject),设置head中的accept字段,当响应返回的时候再调用合适的HttpMessageConvert进行响应转换
  9. ResponseEntity<JSONObject> responseEntity=restTemplate.postForEntity(url,params,JSONObject.class);
  10. int statusCodeValue = responseEntity.getStatusCodeValue();
  11. HttpHeaders headers = responseEntity.getHeaders();
  12. JSONObject body = responseEntity.getBody();

2. 添加Header和Cookie

有时候,我们需要在请求中的Head中添加值或者将某些值通过cookie传给服务端,那么上面这种调用形式就不太满足要求了。

  1. UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl("127.0.0.1:8080").
  2. path("/test").build(true);
  3. URI uri = uriComponents.toUri();
  4. RequestEntity<JSONObject> requestEntity = RequestEntity.post(uri).
  5. //添加cookie(这边有个问题,假如我们要设置cookie的生命周期,作用域等参数我们要怎么操作)
  6. header(HttpHeaders.COOKIE,"key1=value1").
  7. //添加header
  8. header(("MyRequestHeader", "MyValue")
  9. accept(MediaType.APPLICATION_JSON).
  10. contentType(MediaType.APPLICATION_JSON).
  11. body(requestParam);
  12. ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(requestEntity,JSONObject.class);
  13. //响应结果
  14. JSONObject responseEntityBody = responseEntity.getBody();

3. 文件上传

上面两个列子基本能覆盖我们平时开发的大多数功能了。这边再讲个文件上传的列子(RestTemplate功能还是蛮全的)。

  1. public Object uplaod(@RequestBody JSONObject params) throws Exception{
  2. final String url = "http://localhost:8888/hello/m3";
  3. //设置请求头
  4. HttpHeaders headers = new HttpHeaders();
  5. headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  6. //设置请求体,注意是LinkedMultiValueMap
  7. FileSystemResource resource1 = new FileSystemResource("D:\\dir1\\ss\\pic1.jpg");
  8. FileSystemResource resource2 = new FileSystemResource("D:\\dir1\\ss\\pic2.jpg");
  9. MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
  10. form.add("file", resource1);
  11. form.add("file", resource2);
  12. form.add("param1","value1");
  13. HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
  14. JSONObject s = restTemplate.postForObject(url, files, JSONObject.class);
  15. return s;
  16. }

上面的代码中上传了两个本地图片,通过下面代码可以顺利接收。

  1. @RequestMapping("/m3")
  2. public Object fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception {
  3. //携带的其他参数可以使用getParameter方法接收
  4. String param1 = request.getParameter("param1");
  5. Response response = new Response();
  6. if (files == null) {
  7. response.failure("文件上传错误,服务端未拿到上传的文件!");
  8. return response;
  9. }
  10. for (MultipartFile file : files) {
  11. if (!file.isEmpty() && file.getSize() > 0) {
  12. String fileName = file.getOriginalFilename();
  13. //参考FileCopyUtils这个工具类
  14. file.transferTo(new File("D:\\" + fileName));
  15. logger.info("文件:{} 上传成功...",fileName);
  16. }
  17. }
  18. response.success("文件上传成功");
  19. return response;
  20. }

但是我们发现上面的上传代码中,上传文件的类必须使用FileSystemResource。有时我们会碰到这种情况:文件我们会从文件服务下载到内存中一个InputStream的形式存在,那此时在使用FileSystemResource就不行了。

当然,我们使用讨巧一点的办法也是可以的:先将下载下来的InputStream保存到本地,然后再读取到FileSystemResource,上传后再删除本地临时文件。

但是总觉得这个方法不够完美。最后发现有个同事已经写了相关的实现。这边就直接拿来用了。

  1. //自己实现了一个Resource
  2. public class InMemoryResource extends ByteArrayResource {
  3. private final String filename;
  4. private final long lastModified;
  5. public InMemoryResource(String filename, String description, byte[] content, long lastModified) {
  6. super(content, description);
  7. this.lastModified = lastModified;
  8. this.filename = filename;
  9. }
  10. @Override
  11. public long lastModified() throws IOException {
  12. return this.lastModified;
  13. }
  14. @Override
  15. public String getFilename() {
  16. return this.filename;
  17. }
  18. }

调整后的上传代码

  1. @PostMapping("/m3")
  2. public Object m3(@RequestBody JSONObject params) throws Exception{
  3. final String url = "http://localhost:8888/hello/m3";
  4. //设置请求头
  5. HttpHeaders headers = new HttpHeaders();
  6. headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  7. //设置请求体,注意是LinkedMultiValueMap
  8. //下面两个流从文件服务下载,这边省略(注意最后关闭流)
  9. InputStream fis1 =
  10. InputStream fis2 =
  11. InMemoryResource resource1 = new InMemoryResource("file1.jpg","description1", FileCopyUtils.copyToByteArray(fis1), System.currentTimeMillis());
  12. InMemoryResource resource2 = new InMemoryResource("file2.jpg","description2", FileCopyUtils.copyToByteArray(fis2), System.currentTimeMillis());
  13. MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
  14. form.add("file", resource1);
  15. form.add("file", resource2);
  16. form.add("param1","value1");
  17. HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
  18. JSONObject s = restTemplate.postForObject(url, files, JSONObject.class);
  19. return s;
  20. }

一些其他设置#

1. 拦截器配置

RestTemplate也可以设置拦截器做一些统一处理。这个功能感觉和Spring MVC的拦截器类似。配置也很简单:

  1. class MyInterceptor implements ClientHttpRequestInterceptor{
  2. @Override
  3. public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
  4. logger.info("enter interceptor...");
  5. return execution.execute(request,body);
  6. }
  7. }
  8. @Bean
  9. public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  10. RestTemplate restTemplate = new RestTemplate(factory);
  11. MyInterceptor myInterceptor = new MyInterceptor();
  12. List<ClientHttpRequestInterceptor> list = new ArrayList<>();
  13. list.add(myInterceptor);
  14. restTemplate.setInterceptors(list);
  15. return restTemplate;
  16. }

2. ErrorHandler配置

ErrorHandler用来对调用错误对统一处理。

  1. public class MyResponseErrorHandler extends DefaultResponseErrorHandler {
  2. @Override
  3. public boolean hasError(ClientHttpResponse response) throws IOException {
  4. return super.hasError(response);
  5. }
  6. @Override
  7. public void handleError(ClientHttpResponse response) throws IOException {
  8. HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
  9. if (statusCode == null) {
  10. throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
  11. response.getHeaders(), getResponseBody(response), getCharset(response));
  12. }
  13. handleError(response, statusCode);
  14. }
  15. @Override
  16. protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
  17. switch (statusCode.series()) {
  18. case CLIENT_ERROR:
  19. HttpClientErrorException exp1 = new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));
  20. logger.error("客户端调用异常",exp1);
  21. throw exp1;
  22. case SERVER_ERROR:
  23. HttpServerErrorException exp2 = new HttpServerErrorException(statusCode, response.getStatusText(),
  24. response.getHeaders(), getResponseBody(response), getCharset(response));
  25. logger.error("服务端调用异常",exp2);
  26. throw exp2;
  27. default:
  28. UnknownHttpStatusCodeException exp3 = new UnknownHttpStatusCodeException(statusCode.value(), response.getStatusText(),
  29. response.getHeaders(), getResponseBody(response), getCharset(response));
  30. logger.error("网络调用未知异常");
  31. throw exp3;
  32. }
  33. }
  34. }
  35. @Bean
  36. public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  37. RestTemplate restTemplate = new RestTemplate(factory);
  38. MyResponseErrorHandler errorHandler = new MyResponseErrorHandler();
  39. restTemplate.setErrorHandler(errorHandler);
  40. List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
  41. //通过下面代码可以添加新的HttpMessageConverter
  42. //messageConverters.add(new );
  43. return restTemplate;
  44. }

3. HttpMessageConverter配置
RestTemplate 也可以配置HttpMessageConverter,配置的原理和Spring MVC中类似。

简单总结#

通过RestTemplate,我们可以非常方便的进行Rest API调用。但是在Spring 5中已经不再建议使用RestTemplate,而是建议使用WebClient。WebClient是一个支持异步调用的Client。所以喜欢研究新东西的同学可以开始研究下新东西了。

同步RestTemplate和异步AsyncRestTemplate

我编写了以下代码来测试同步RestTemplate和AsyncRestTemplate的性能.我只是在POSTMAN上手动运行了几次.

我们只是将10个引用传递给GET调用,以便我们可以返回10个链接:

RestTemplate – 同步并在2806ms返回:

  1. ArrayList<String> references = new ArrayList<>();
  2. ArrayList<String> links = new ArrayList<>();
  3. RestTemplate restTemplate = new RestTemplate();
  4. restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
  5. for (int i = 0; i < 10; i++) {
  6. ResponseEntity<String> resource = restTemplate.getForEntity(references.get(i), String.class);
  7. links.add(resource.getBody().toString());
  8. }
  9. 复制代码

RestTemplate – 异步并返回2794ms:

  1. //Creating a synchronizedList so that when the async resttemplate returns, there will be no concurrency issues
  2. List<String> links = Collections.synchronizedList(new ArrayList<String>());
  3. //CustomClientHttpRequestFactory just extends SimpleClientHttpRequestFactory but disables automatic redirects in SimpleClientHttpRequestFactory
  4. CustomClientHttpRequestFactory customClientHttpRequestFactory = new CustomClientHttpRequestFactory();
  5. //Setting the ThreadPoolTaskExecutor for the Async calls
  6. org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor pool = new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor();
  7. pool.setCorePoolSize(5);
  8. pool.setMaxPoolSize(10);
  9. pool.setWaitForTasksToCompleteOnShutdown(true);
  10. pool.initialize();
  11. //Setting the TaskExecutor to the ThreadPoolTaskExecutor
  12. customClientHttpRequestFactory.setTaskExecutor(pool);
  13. ArrayList<String> references = new ArrayList<>();
  14. ArrayList<String> links = new ArrayList<>();
  15. AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(customClientHttpRequestFactory);
  16. restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
  17. for (int i = 0; i < 10; i++) {
  18. Future<ResponseEntity<String>> resource = asyncRestTemplate.getForEntity(references.get(i), String.class);
  19. ResponseEntity<String> entity = resource.get(); //this should start up 10 threads to get the links asynchronously
  20. links.add(entity.getBody().toString());
  21. }
  22. 复制代码

在大多数情况下,两种方法实际上都以非常相似的时间返回结果,在异步和同步调用中平均为2800ms.

我做错了什么,因为我希望异步调用更快?

最佳答案

我会说你在这里错过了AsyncRest的真正好处.
您应该为要发送的每个请求添加回调,以便响应仅在可用时进行处理.

实际上,AsyncRestTemplate的getForEntity方法返回一个可以连接回调任务的ListenableFuture.有关详细信息,请参阅官方文档ListenableFuture.

例如,在您的情况下,它可能是:

  1. for (int i = 0; i < 10; i++) {
  2. ListenableFuture<ResponseEntity<String>> response = asyncRestTemplate.getForEntity(references.get(i), String.class);
  3. response.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
  4. @Override
  5. public void onSuccess(ResponseEntity<String> result) {
  6. // Do stuff onSuccess
  7. links.add(result.getBody().toString());
  8. }
  9. @Override
  10. public void onFailure(Throwable ex) {
  11. log.warn("Error detected while submitting a REST request. Exception was {}", ex.getMessage());
  12. }
  13. });
  14. }

#

RestTemplate整合HttpClient、Okhttp

HttpClient入门

  • 确定maven环境

    1. <parent>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-parent</artifactId>
    4. <version>2.1.4.RELEASE</version>
    5. </parent>
    6. <dependencies>
    7. <!--web起步依赖-->
    8. <dependency>
    9. <groupId>org.springframework.boot</groupId>
    10. <artifactId>spring-boot-starter-web</artifactId>
    11. </dependency>
    12. <!--httpclient-->
    13. <dependency>
    14. <groupId>org.apache.httpcomponents</groupId>
    15. <artifactId>httpclient</artifactId>
    16. <version>4.5.6</version>
    17. </dependency>
    18. <!--支持lombok-->
    19. <dependency>
    20. <groupId>lombok</groupId>
    21. <artifactId>lombok</artifactId>
    22. <version>1.0</version>
    23. </dependency>
    24. <!--fastjson-->
    25. <dependency>
    26. <groupId>com.alibaba</groupId>
    27. <artifactId>fastjson</artifactId>
    28. <version>1.2.49</version>
    29. </dependency>
    30. <dependency>
    31. <groupId>org.springframework.boot</groupId>
    32. <artifactId>spring-boot-starter-test</artifactId>
    33. </dependency>
    34. </dependencies>
  • 使用HttpClient发送Get请求

    CloseableHttpClient httpClient = null;

    1. CloseableHttpResponse response = null;
    2. try {
    3. //1 创建Httpclient对象(默认连接),相当于打开了浏览器
    4. CloseableHttpClient httpClient = HttpClients.createDefault();
    5. //2 确定请求方式和请求路径,相当于在浏览器输入地址
    6. HttpGet httpGet = new HttpGet("http://localhost:9090/user");
    7. //3 执行请求并获取响应,相当于敲完地址后按下回车。
    8. CloseableHttpResponse response = httpClient.execute(httpGet);
    9. //4 判断状态码
    10. if(response.getStatusLine().getStatusCode() == 200){
    11. //5.1 获得响应数据的类型
    12. System.out.println(response.getEntity().getContentType());
    13. //5.2 获得响应体内容并使用EntityUtils工具进行处理
    14. String str = EntityUtils.toString(response.getEntity(),"UTF-8");
    15. System.out.println(str);
    16. }
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }finally {
    20. //6 释放资源
    21. response.close();
    22. httpClient.close();
    23. }
  • 使用HttpClient发送Post请求

    1. CloseableHttpClient httpClient = null;
    2. CloseableHttpResponse response = null;
    3. try {
    4. httpClient = HttpClients.createDefault();
    5. HttpPost httpPost = new HttpPost("http://localhost:9090/user");
    6. // 设置请求头
    7. httpPost.setHeader("content-type","application/json;charset=utf-8");
    8. // 设置并处理请求体
    9. String str = "{\"username\":\"jack\",\"password\":\"1111\"}";
    10. httpPost.setEntity(new StringEntity(str,"utf-8"));
    11. response = httpClient.execute(httpPost);
    12. if (response.getStatusLine().getStatusCode() == 200){
    13. System.out.println(EntityUtils.toString(response.getEntity()));
    14. }
    15. } catch (IOException e) {
    16. e.printStackTrace();
    17. }finally {
    18. response.close();
    19. httpClient.close();
    20. }
  • 使用HttpClient发送Put请求

    1. CloseableHttpClient httpClient = null;
    2. CloseableHttpResponse response = null;
    3. try {
    4. httpClient = HttpClients.createDefault();
    5. HttpPut httpPut = new HttpPut("http://localhost:9090/user");
    6. httpPut.setHeader("content-type","application/json;charset=utf-8");
    7. String jsonStr = JSON.toJSONString(new User(1, "jack", "1111", 18));
    8. httpPut.setEntity(new StringEntity(jsonStr,"utf-8"));
    9. response = httpClient.execute(httpPut);
    10. if (response.getStatusLine().getStatusCode() == 200){
    11. System.out.println(EntityUtils.toString(response.getEntity()));
    12. }
    13. } catch (IOException e) {
    14. e.printStackTrace();
    15. } finally {
    16. response.close();
    17. httpClient.close();
    18. }
  • 使用HttpClient发送Delete请求

    1. CloseableHttpClient httpClient = null;
    2. CloseableHttpResponse response = null;
    3. try {
    4. //1, 创建客户端
    5. httpClient = HttpClients.createDefault();
    6. //2, 创建DELETE实例
    7. HttpDelete httpDelete = new HttpDelete("http://localhost:9090/user/1");
    8. //3, 发送请求
    9. response = httpClient.execute(httpDelete);
    10. //4, 判断状态码
    11. if (response.getStatusLine().getStatusCode() == 200){
    12. //5, 实用工具处理响应数据
    13. System.out.println(EntityUtils.toString(response.getEntity()));
    14. }
    15. } catch (IOException e) {
    16. e.printStackTrace();
    17. } finally {
    18. //6, 释放资源
    19. response.close();
    20. httpClient.close();
    21. }

4.RestTemplate

  • RestTemplate是Spring提供的用于访问Rest服务的客户端,

    ​ RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率

  • Get请求

    1. [@Test](https://my.oschina.net/azibug)
    2. public void testGet(){
    3. RestTemplate restTemplate = new RestTemplate();
    4. // 设置url,返回值类型
    5. ResponseEntity<BaseResult> entity = restTemplate.getForEntity("http://localhost:9090/user", BaseResult.class);
    6. // 返回状态码
    7. System.out.println(entity.getStatusCode());
    8. // 返回响应体
    9. System.out.println(entity.getBody().getData());
    10. }
  • Post请求

    1. [@Test](https://my.oschina.net/azibug)
    2. public void testLogin(){
    3. RestTemplate restTemplate = new RestTemplate();
    4. // 设置url,请求体(自动处理),返回值类型
    5. ResponseEntity<User> entity = restTemplate.postForEntity("http://localhost:9090/user/login", new User(1,"jack","1234",18), User.class);
    6. System.out.println(entity.getStatusCodeValue());
    7. System.out.println(entity.getBody());
    8. }
  • Put请求

    1. [@Test](https://my.oschina.net/azibug)
    2. public void testPut(){
    3. RestTemplate restTemplate = new RestTemplate();
    4. // 设置url
    5. restTemplate.put("http://localhost:9090/user",new User(1,"jack","1234",18));
    6. System.out.println("修改成功");
    7. }
  • Delete请求

    1. [@Test](https://my.oschina.net/azibug)
    2. public void testDelete(){
    3. RestTemplate restTemplate = new RestTemplate();
    4. // 设置url
    5. restTemplate.delete("http://localhost:9090/user/1");
    6. System.out.println(" 删除成功");
    7. }

5.SpringBoot 整合 HttpClient及RestTemplate自定义连接池

  1. package com.czxy.config;
  2. import org.apache.http.client.HttpClient;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.http.client.ClientHttpRequestFactory;
  10. import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
  11. import org.springframework.http.converter.HttpMessageConverter;
  12. import org.springframework.http.converter.StringHttpMessageConverter;
  13. import org.springframework.web.client.RestTemplate;
  14. import java.nio.charset.Charset;
  15. import java.util.List;
  16. /**
  17. * Created by 澈 on 2019/12/3.
  18. */
  19. @Configuration
  20. public class HttpClientConfig {
  21. //1. 自定义连接 httpClient
  22. @Bean
  23. public CloseableHttpClient httpClient(PoolingHttpClientConnectionManager connectionManager,
  24. RequestConfig requestConfig){
  25. return HttpClients.custom()
  26. .setConnectionManager(connectionManager)
  27. .setDefaultRequestConfig(requestConfig)
  28. .build();
  29. }
  30. //2. 配置PoolingHttpClientConnectionManager
  31. @Bean
  32. public PoolingHttpClientConnectionManager connectionManager(){
  33. //1. HttpClient连接管理器
  34. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
  35. //1.1. 最大连接数
  36. connectionManager.setMaxTotal(1000);
  37. //1.2. 设置并发访问数
  38. connectionManager.setDefaultMaxPerRoute(20);
  39. return connectionManager;
  40. }
  41. //3. 配置RequestConfig
  42. @Bean
  43. public RequestConfig requestConfig(){
  44. //1.3. 请求配置RequestConfig
  45. return RequestConfig.custom()
  46. .setConnectTimeout(1000)
  47. .setConnectionRequestTimeout(500)
  48. .setSocketTimeout(10 * 1000)
  49. .build();
  50. }
  51. //4. 创建一个工厂
  52. @Bean
  53. public ClientHttpRequestFactory requestFactory(HttpClient httpClient){
  54. return new HttpComponentsClientHttpRequestFactory(httpClient);
  55. }
  56. //5. 配置restTemplate
  57. @Bean
  58. public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
  59. RestTemplate template = new RestTemplate(requestFactory);
  60. //乱码处理
  61. List<HttpMessageConverter<?>> list = template.getMessageConverters();
  62. for (HttpMessageConverter<?> mc : list) {
  63. if (mc instanceof StringHttpMessageConverter) {
  64. ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
  65. }
  66. }
  67. return template;
  68. }
  69. }

6.整合SpringBoot测试类

  • 在测试代码中可以进行Spring容器的注册

    package com.czxy;

    import com.alibaba.fastjson.JSON;
    import com.czxy.domain.User;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.util.EntityUtils;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.web.client.RestTemplate;

    import javax.annotation.Resource;
    import java.io.IOException;

    /**

    • Created by 澈 on 2019/12/4.
      */
      @RunWith(SpringRunner.class) //spring 整合junit
      @SpringBootTest(classes = HttpClientApplication.class) //spring整合启动类
      public class Test04 {

      @Resource
      private CloseableHttpClient httpClient;
      @Resource
      private RestTemplate restTemplate;
      @Resource
      private PoolingHttpClientConnectionManager connectionManager;
      @Resource
      private RequestConfig requestConfig;

      @Test
      public void testDemo02(){

      1. System.out.println(httpClient);
      2. System.out.println(restTemplate);
      3. System.out.println(connectionManager);
      4. System.out.println(requestConfig);

      }
      }

springboot装配OkHttp组件

在SpringBoot应用中,发送Http通常我们使用RestTemplate,但有部分组件底层是使用OkHttp进行Http的操作,而且OKHttp也是一个很优秀的HTTP组件。

RestTempate的springboot封装参考:https://www.cnblogs.com/yangzhilong/p/6640207.html

application.yml

  1. okhttp:
  2. connect-timeout-ms: 500
  3. keep-alive-duration-sec: 5000
  4. max-idle: 100
  5. read-timeout-ms: 500
  6. write-timeout-ms: 500

Configuration:

复制代码

  1. import java.util.concurrent.TimeUnit;
  2. import javax.annotation.Resource;
  3. import javax.validation.constraints.NotNull;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.validation.annotation.Validated;
  8. import com.longge.gateway.util.OkHttpUtils;
  9. import lombok.Getter;
  10. import lombok.Setter;
  11. import okhttp3.ConnectionPool;
  12. import okhttp3.OkHttpClient;
  13. /**
  14. * @author roger yang
  15. * @date 9/16/2019
  16. */
  17. public class OkHttpConfiguration {
  18. @Resource
  19. private OkHttpConfig okHttpConfig;
  20. @Bean
  21. public OkHttpClient okHttpClient() {
  22. OkHttpClient client = new OkHttpClient.Builder()
  23. .retryOnConnectionFailure(false)
  24. .connectionPool(pool())
  25. .connectTimeout(okHttpConfig.getConnectTimeoutMs(), TimeUnit.MILLISECONDS)
  26. .readTimeout(okHttpConfig.getReadTimeoutMs(), TimeUnit.MILLISECONDS)
  27. .writeTimeout(okHttpConfig.getWriteTimeoutMs(),TimeUnit.MILLISECONDS)
  28. .build();
  29. OkHttpUtils.setOkHttpClient(client);
  30. return client;
  31. }
  32. @Bean
  33. public ConnectionPool pool() {
  34. return new ConnectionPool(okHttpConfig.getMaxIdle(), okHttpConfig.getKeepAliveDurationSec(), TimeUnit.SECONDS);
  35. }
  36. @Component
  37. @ConfigurationProperties(prefix = "okhttp")
  38. @Getter
  39. @Setter
  40. @Validated
  41. static class OkHttpConfig {
  42. @NotNull
  43. private Long connectTimeoutMs;
  44. @NotNull
  45. private Long readTimeoutMs;
  46. @NotNull
  47. private Long writeTimeoutMs;
  48. @NotNull
  49. private Integer maxIdle;
  50. @NotNull
  51. private Long keepAliveDurationSec;
  52. }
  53. }

复制代码

Util帮助类:

复制代码

  1. import java.io.IOException;
  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import java.util.Map;
  5. import java.util.Objects;
  6. import com.alibaba.fastjson.JSONObject;
  7. import lombok.NonNull;
  8. import okhttp3.Callback;
  9. import okhttp3.FormBody;
  10. import okhttp3.Headers;
  11. import okhttp3.MediaType;
  12. import okhttp3.OkHttpClient;
  13. import okhttp3.Request;
  14. import okhttp3.RequestBody;
  15. import okhttp3.Response;
  16. /**
  17. * 参数中Callback表示发送异步请求
  18. * @author roger yang
  19. * @date 9/16/2019
  20. */
  21. public class OkHttpUtils {
  22. private static OkHttpClient okHttpClient;
  23. public static void setOkHttpClient(OkHttpClient client) {
  24. okHttpClient = client;
  25. }
  26. /**
  27. * GET Method begin---------------------------------
  28. */
  29. public static <T> T get(@NonNull String url, Class<T> clasz) {
  30. return get(url, null, null, clasz);
  31. }
  32. public static void get(@NonNull String url, Callback callback) {
  33. get(url, null, null, callback);
  34. }
  35. public static <T> T get(@NonNull String url, Map<String, String> queryParameter, Class<T> clasz) {
  36. return get(url, null, queryParameter, clasz);
  37. }
  38. public static void get(@NonNull String url, Map<String, String> queryParameter, Callback callback) {
  39. get(url, null, queryParameter, callback);
  40. }
  41. public static <T> T get(@NonNull String url, Map<String, String> headerParameter, Map<String, String> queryParameter, Class<T> clasz) {
  42. Request request = processGetParameter(url, headerParameter, queryParameter);
  43. try (Response resp = okHttpClient.newCall(request).execute();) {
  44. return processResponse(resp, clasz);
  45. } catch (Exception e) {
  46. throw new RuntimeException(e);
  47. }
  48. }
  49. public static void get(@NonNull String url, Map<String, String> headerParameter, Map<String, String> queryParameter, Callback callback) {
  50. Request request = processGetParameter(url, headerParameter, queryParameter);
  51. okHttpClient.newCall(request).enqueue(callback);
  52. }
  53. private static Request processGetParameter(String url, Map<String, String> headerParameter, Map<String, String> queryParameter) {
  54. Request.Builder builder = new Request.Builder();
  55. if (!isEmptyMap(headerParameter)) {
  56. builder.headers(Headers.of(headerParameter));
  57. }
  58. if (isEmptyMap(queryParameter)) {
  59. builder.url(url);
  60. } else {
  61. boolean hasQuery = false;
  62. try {
  63. hasQuery = new URL(url).getQuery().isEmpty();
  64. } catch (MalformedURLException e) {
  65. throw new RuntimeException("url is illegal");
  66. }
  67. StringBuilder sb = new StringBuilder(url);
  68. if (!hasQuery) {
  69. sb.append("?1=1");
  70. }
  71. queryParameter.forEach((k, v) -> {
  72. sb.append("&").append(k).append("=").append(v);
  73. });
  74. builder.url(sb.toString());
  75. }
  76. return builder.build();
  77. }
  78. /**
  79. * POST Method With JSON begin---------------------------------
  80. */
  81. public static <T> T postJson(@NonNull String url, Class<T> clasz) {
  82. return postJson(url, null, null, clasz);
  83. }
  84. public static void postJson(@NonNull String url, Callback callback) {
  85. postJson(url, null, null, callback);
  86. }
  87. public static <T> T postJson(@NonNull String url, Map<String, String> headerParameter, Class<T> clasz) {
  88. return postJson(url, headerParameter, null, clasz);
  89. }
  90. public static void postJson(@NonNull String url, Map<String, String> headerParameter, Callback callback) {
  91. postJson(url, headerParameter, null, callback);
  92. }
  93. public static <T> T postJson(@NonNull String url, Map<String, String> headerParameter, Object bodyObj, Class<T> clasz) {
  94. Request request = processPostJsonParameter(url, headerParameter, bodyObj);
  95. try (Response resp = okHttpClient.newCall(request).execute();) {
  96. return processResponse(resp, clasz);
  97. } catch (Exception e) {
  98. throw new RuntimeException(e);
  99. }
  100. }
  101. public static void postJson(@NonNull String url, Map<String, String> headerParameter, Object bodyObj, Callback callback) {
  102. Request request = processPostJsonParameter(url, headerParameter, bodyObj);
  103. okHttpClient.newCall(request).enqueue(callback);
  104. }
  105. private static Request processPostJsonParameter(String url, Map<String, String> headerParameter, Object bodyObj) {
  106. Request.Builder builder = new Request.Builder().url(url);
  107. if(!Objects.isNull(bodyObj)) {
  108. RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSONObject.toJSONString(bodyObj));
  109. builder.post(body);
  110. } else {
  111. RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{}");
  112. builder.post(body);
  113. }
  114. if (!isEmptyMap(headerParameter)) {
  115. builder.headers(Headers.of(headerParameter));
  116. }
  117. return builder.build();
  118. }
  119. /**
  120. * POST Method With Form begin---------------------------------
  121. */
  122. public static <T> T postForm(@NonNull String url, Class<T> clasz) {
  123. return postForm(url, null, null, clasz);
  124. }
  125. public static void postForm(@NonNull String url, Callback callback) {
  126. postForm(url, null, null, callback);
  127. }
  128. public static <T> T postForm(@NonNull String url, Map<String, String> headerParameter, Class<T> clasz) {
  129. return postForm(url, headerParameter, null, clasz);
  130. }
  131. public static void postForm(@NonNull String url, Map<String, String> headerParameter, Callback callback) {
  132. postForm(url, headerParameter, null, callback);
  133. }
  134. public static <T> T postForm(@NonNull String url, Map<String, String> headerParameter, Map<String, String> parameters, Class<T> clasz) {
  135. Request request = processPostFormParameter(url, headerParameter, parameters);
  136. try (Response resp = okHttpClient.newCall(request).execute();) {
  137. return processResponse(resp, clasz);
  138. } catch (Exception e) {
  139. throw new RuntimeException(e);
  140. }
  141. }
  142. public static void postForm(@NonNull String url, Map<String, String> headerParameter, Map<String, String> parameters, Callback callback) {
  143. Request request = processPostFormParameter(url, headerParameter, parameters);
  144. okHttpClient.newCall(request).enqueue(callback);
  145. }
  146. private static Request processPostFormParameter(String url, Map<String, String> headerParameter, Map<String, String> parameters) {
  147. Request.Builder builder = new Request.Builder().url(url);
  148. if(!Objects.isNull(parameters)) {
  149. FormBody.Builder formBuilder = new FormBody.Builder();
  150. parameters.forEach((k, v) -> {
  151. formBuilder.add(k, v);
  152. });
  153. builder.post(formBuilder.build());
  154. }
  155. if (!isEmptyMap(headerParameter)) {
  156. builder.headers(Headers.of(headerParameter));
  157. }
  158. return builder.build();
  159. }
  160. @SuppressWarnings("unchecked")
  161. private static <T> T processResponse(Response resp, Class<T> clasz) throws IOException {
  162. if (resp.isSuccessful()) {
  163. if (Objects.equals(Void.class, clasz)) {
  164. return null;
  165. }
  166. String respStr = resp.body().string();
  167. if(Objects.equals(String.class, clasz)) {
  168. return (T)respStr;
  169. }
  170. return JSONObject.parseObject(respStr, clasz);
  171. }
  172. return null;
  173. }
  174. private static boolean isEmptyMap(Map<? extends Object, ? extends Object> map) {
  175. return Objects.isNull(map) || map.isEmpty();
  176. }
  177. }

复制代码

GitHub地址:https://github.com/yangzhilong/new-gateway-test.git

如果想要OkHttp的装配是非自动的,可以采用自定义@EnableXX注解来实现。

复制代码

  1. import java.lang.annotation.Documented;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. import org.springframework.context.annotation.Import;
  7. import com.longge.gateway.configuration.OkHttpConfiguration;
  8. /**
  9. * @author roger yang
  10. * @date 9/16/2019
  11. */
  12. @Target(ElementType.TYPE)
  13. @Retention(RetentionPolicy.RUNTIME)
  14. @Documented
  15. @Import(OkHttpConfiguration.class)
  16. public @interface EnableOkHttp {
  17. }

复制代码

然后把OkHttpConfiguration类的@Configuration注解去掉,当你要用时在启动类加上@EnableOkHttp即可。

对于OKhttp的设置还可参考:

1、简介

OkHttp是一个高效的HTTP客户端,允许所有同一个主机地址的请求共享同一个socket连接;连接池减少请求延时;透明的GZIP压缩减少响应数据的大小;缓存响应内容,避免一些完全重复的请求

当网络出现问题的时候OkHttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个IP地址,当第一个IP请求失败时,OkHttp会交替尝试你配置的其他IP,OkHttp使用现代TLS技术(SNI, ALPN)初始化新的连接,当握手失败时会回退到TLS 1.0。

1)使用:它的请求/响应 API 使用构造器模式builders来设计,它支持阻塞式的同步请求和带回调的异步请求。

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>3.10.0</version>
  5. </dependency>
  6. import okhttp3.ConnectionPool;
  7. import okhttp3.OkHttpClient;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.http.client.ClientHttpRequestFactory;
  11. import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
  12. import org.springframework.web.client.RestTemplate;
  13. import javax.net.ssl.SSLContext;
  14. import javax.net.ssl.SSLSocketFactory;
  15. import javax.net.ssl.TrustManager;
  16. import javax.net.ssl.X509TrustManager;
  17. import java.security.KeyManagementException;
  18. import java.security.NoSuchAlgorithmException;
  19. import java.security.SecureRandom;
  20. import java.security.cert.CertificateException;
  21. import java.security.cert.X509Certificate;
  22. import java.util.concurrent.TimeUnit;
  23. @Configuration
  24. public class OkHttpRestTemplateConfig {
  25. @Bean("okHttpRestTemplate")
  26. public RestTemplate okHttpRestTemplate() {
  27. OkHttpClient httpClient = okHttpClient();
  28. ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(httpClient);
  29. RestTemplate restTemplate = new RestTemplate(factory);
  30. // 可以添加消息转换
  31. //restTemplate.setMessageConverters(...);
  32. // 可以增加拦截器
  33. //restTemplate.setInterceptors(...);
  34. return restTemplate;
  35. }
  36. @Bean
  37. public OkHttpClient okHttpClient() {
  38. return new OkHttpClient.Builder()
  39. //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
  40. .retryOnConnectionFailure(false)
  41. .connectionPool(pool())
  42. .connectTimeout(30, TimeUnit.SECONDS)
  43. .readTimeout(30, TimeUnit.SECONDS)
  44. .writeTimeout(30,TimeUnit.SECONDS)
  45. .build();
  46. }
  47. @Bean
  48. public X509TrustManager x509TrustManager() {
  49. return new X509TrustManager() {
  50. @Override
  51. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  52. }
  53. @Override
  54. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  55. }
  56. @Override
  57. public X509Certificate[] getAcceptedIssuers() {
  58. return new X509Certificate[0];
  59. }
  60. };
  61. }
  62. @Bean
  63. public SSLSocketFactory sslSocketFactory() {
  64. try {
  65. //信任任何链接
  66. SSLContext sslContext = SSLContext.getInstance("TLS");
  67. sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
  68. return sslContext.getSocketFactory();
  69. } catch (NoSuchAlgorithmException e) {
  70. e.printStackTrace();
  71. } catch (KeyManagementException e) {
  72. e.printStackTrace();
  73. }
  74. return null;
  75. }
  76. /**
  77. * Create a new connection pool with tuning parameters appropriate for a single-user application.
  78. * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
  79. */
  80. @Bean
  81. public ConnectionPool pool() {
  82. return new ConnectionPool(200, 5, TimeUnit.MINUTES);
  83. }
  84. }

发表评论

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

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

相关阅读

    相关 RestTemplate使用详解

    在开发中有时候经常需要一些Http请求,请求数据,下载内容,也有一些简单的分布式应用直接使用Http请求作为跨应用的交互协议。 在Java中有不同的Http请求方式,主要就是

    相关 详解 RestTemplate 操作

    详解 RestTemplate 操作 作为开发人员,我们经常关注于构建伟大的软件来解决业务问题。数据只是软件完成工作时 要处理的原材料。但是如果你问一下业务人员,数据

    相关 详解 RestTemplate 操作

    详解 RestTemplate 操作 作为开发人员,我们经常关注于构建伟大的软件来解决业务问题。数据只是软件完成工作时  要处理的原材料。但是如果你问一下业务人员,数