Spring Rest Client之RestTemplate

目录

概述

使用GET方式获取资源

通过普通的JSON格式

通过POJO方式

使用Head去获取header

使用POST方式去创建资源

postForObject()

exchange()

提交表单

使用OPTION获取可操作的类型 

使用PUT来更新资源

使用DELETE来删除资源

设置超时时间


概述

本篇文章将介绍如何使用RestTemplate,需要注意的是新版的spring framework,由于有WebFlux的加持,Spring提供了一个新版的Rest Client,叫做WebClient,用来替代RestTemplate,WebClient可以提供传统RestTemplate的同步调用,也可以提供异步非阻塞的方式调用。如果你在构建一个新的服务或者在进行系统升级,考虑使用WebClient,因为在之后的版本中spring将会逐步弃用RestTemplate。

使用GET方式获取资源

通过普通的JSON格式

一个最简单的例子就是通过getForEntity(),可以获取到返回的所有内容

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl
  = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response
  = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.OK);

如果我们需要响应中的某些字段,则需要使用Jackson包去解析字符串

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode name = root.path("name");
Assertions.assertNotNull(name.asText());

通过POJO方式

如果我们只关心返回消息体内容,我们使用POJO方式,则需要有一个DTO,用来转化资源格式。

public class Foo implements Serializable {
    private long id;

    private String name;
    // getters and setters
}
Foo foo = restTemplate
  .getForObject(fooResourceUrl + "/1", Foo.class);
Assertions.assertNotNull(foo.getName());
Assertions.assertEquals(foo.getId(), 1L);

使用Head去获取header

HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
Assertions.assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));

使用POST方式去创建资源

postForObject()

RestTemplate restTemplate = new RestTemplate();

HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
Assertions.assertNotNull(foo);
Assertions.assertEquals(foo.getName(), "bar");

exchange()

RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
ResponseEntity<Foo> response = restTemplate
  .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
 
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);
 
Foo foo = response.getBody();
 
Assertions.assertNotNull(foo);
Assertions.assertEquals(foo.getName(), "bar");

提交表单

如果是表单格式的数据我们首先要将ContentType设置成application/x-www-form-urlencoded,

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

将数据封装到Map中 ,并构建HttpEntity,

MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "1");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

最后,我们通过调用postForEntity完成调用。

ResponseEntity<String> response = restTemplate.postForEntity(
  fooResourceUrl+"/form", request , String.class);
Assertions.assertEquals(response.getStatusCode(), HttpStatus.CREATED);

使用OPTION获取可操作的类型 

可以使用optionsForAllow来获取资源的可操作类型。

Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
HttpMethod[] supportedMethods
  = {HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE};
Assertions.assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));

使用PUT来更新资源

上面在POST来创建资源时,我们使用了exchange(),此时同样也可以使用

Foo updatedInstance = new Foo("newName");
updatedInstance.setId(createResponse.getBody().getId());
String resourceUrl = 
  fooResourceUrl + '/' + createResponse.getBody().getId();
HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);

使用DELETE来删除资源

我们可以直接使用delete方法来删除资源

String entityUrl = fooResourceUrl + "/" + existingResource.getId();
restTemplate.delete(entityUrl);

设置超时时间

RestTemplate默认的connectionTimeout和readTimeout都是0,也就是无限等待。根据项目的需要可以设置相应的超时时间。可以通过使用ClientHttpRequestFactory来设置。

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
      = new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值