1.概述
在本教程中,我们将演示Spring REST Client - .创建RestTemplate——可以被利用,而且利用得很好。
对于所有示例的API端,我们将运行RESTful服务在这里。
进一步阅读:
2.弃用的通知
在Spring框架5中,除了WebFlux堆栈,Spring引入了一个新的HTTP客户端WebClient。
WebClient现代的、可替代的HTTP客户机是创建RestTemplate。它不仅提供传统的同步API,而且还支持有效的非阻塞和异步方法。
也就是说,如果我们在开发新应用程序或迁移旧应用程序,这是个好主意WebClient。在前进的道路上,创建RestTemplate将在未来版本中弃用。
3.使用GET获取资源
3.1。得到纯JSON
让我们从简单的GET请求开始金宝搏官网188be控件的一个快速示例getForEntity ()API:
RestTemplate RestTemplate = new RestTemplate();字符串fooResourceUrl = "http://localhost:8080/spring-rest/foos";响应实体 response = restTemplate。getForEntity(fooResourceUrl +“/1”,String.class);为了(response.getStatusCode(),等于(HttpStatus.OK));
注意,我们可以完全访问HTTP响应,所以我们可以做一些事情,如检查状态代码,以确保操作成功或与实际的响应体工作:
ObjectMapper = new ObjectMapper();JsonNode root = mapper.readTree(response.getBody());JsonNode name = root.path("name");为了(name.asText (), notNullValue ());
我们在这里将响应体作为标准String处理,并使用Jackson(以及Jackson提供的JSON节点结构)来验证一些细节。
3.2。检索POJO而不是JSON
我们还可以将响应直接映射到资源DTO:
public class Foo实现Serializable {private long id;私人字符串名称;//标准的getter和setter}
现在我们可以简单地使用getForObject模板中的API:
Foo Foo = restTemplate .getForObject(fooResourceUrl +“/1”,Foo.class);为了(foo.getName (), notNullValue ());为了(foo.getId(),(1升));
4.使用头部检索头部
现在让我们快速了解一下如何使用HEAD,然后再讨论更常用的方法。
我们将使用headForHeaders ()API在这里:
HttpHeaders = restTemplate.headForHeaders(fooResourceUrl);assertTrue (httpHeaders.getContentType()其中包括(MediaType.APPLICATION_JSON));
5.使用POST创建资源
为了在API中创建新的Resource,我们可以很好地利用postForLocation (),postForObject ()或postForEntity ()api。
第一个返回新创建的资源的URI,而第二个返回资源本身。
5.1。的postForObject ()API
RestTemplate RestTemplate = new RestTemplate();HttpEntity request = new HttpEntity<>(new Foo("bar"));Foo Foo = restTemplate。postForObject (fooResourceUrl、请求Foo.class);为了(foo, notNullValue ());为了(foo.getName(),(“酒吧”));
5.2。的postForLocation ()API
类似地,让我们看看这个操作,它不是返回完整的Resource,而是返回位置新设立的资源:
HttpEntity request = new HttpEntity<>(new Foo("bar"));URI位置= restTemplate .postForLocation(fooResourceUrl,请求);为了(位置,notNullValue ());
5.3。的交换()API
让我们看看如何做一个更通用的POST交换API:
RestTemplate RestTemplate = new RestTemplate();HttpEntity request = new HttpEntity<>(new Foo("bar"));ResponseEntity response = restTemplate .exchange(fooResourceUrl, HttpMethod. name)帖子,请求,Foo.class);为了(response.getStatusCode (), (HttpStatus.CREATED));Foo Foo = response.getBody();为了(foo, notNullValue ());为了(foo.getName(),(“酒吧”));
5.4。提交表单数据
接下来,让我们看看如何使用POST方法提交表单。
首先,我们需要设置内容类型头来应用程序/ x-www-form-urlencoded。
这确保可以将一个大的查询字符串发送到服务器,其中包含由分隔的名称/值对&:
HttpHeaders = new HttpHeaders();headers.setContentType (MediaType.APPLICATION_FORM_URLENCODED);
我们可以把表单变量包装成LinkedMultiValueMap:
MultiValueMap map= new LinkedMultiValueMap<>();地图。添加(“id”,“1”);
接下来,我们使用HttpEntity实例:
HttpEntity> request = new HttpEntity<>(map, headers);
最后,我们可以通过调用连接到REST服务restTemplate.postForEntity ()端点:/喷火/形式
响应实体 response = restTemplate。postForEntity(fooResourceUrl+“/form”,请求,String.class);为了(response.getStatusCode (), (HttpStatus.CREATED));
6.使用OPTIONS获取允许的操作
接下来,我们将快速了解一下使用OPTIONS请求,并研究使用这种请求对特定URI允许的操作;这个APIoptionsForAllow:
设置 optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);HttpMethod[] supportedMethods = {HttpMethod。, HttpMethod。帖子,HttpMethod。把,HttpMethod.DELETE}; assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
7.使用PUT更新资源
接下来,我们将开始研究PUT,更具体地说,是交换()API,因为template.putAPI非常简单。
7.1。简单的把与交换()
我们将从一个简单的针对API的PUT操作开始——请记住,该操作并不是将主体返回给客户端:
Foo updatedInstance = new Foo(“newName”);.getId updatedInstance.setId (createResponse.getBody () ());String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();HttpEntity requestUpdate = new HttpEntity<>(updatedInstance, headers);模板。交换(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
7.2。把与交换()和请求回调
接下来,我们将使用请求回调来发出PUT。
让我们确保我们准备了回调,在那里我们可以设置所有我们需要的头文件和请求体:
RequestCallback RequestCallback (final Foo updatedInstance) {return clientHttpRequest -> {ObjectMapper mapper = new ObjectMapper();mapper.writeValue (clientHttpRequest.getBody (), updatedInstance);clientHttpRequest.getHeaders()。add (HttpHeaders。CONTENT_TYPE MediaType.APPLICATION_JSON_VALUE);clientHttpRequest.getHeaders()。add (HttpHeaders。授权,“基本”+ getBase64EncodedLogPass());};}
接下来,我们用POST请求创建资源:
ResponseEntity response = restTemplate .exchange(fooResourceUrl, HttpMethod. name)帖子,请求,Foo.class);为了(response.getStatusCode (), (HttpStatus.CREATED));
然后我们更新资源:
Foo updatedInstance = new Foo(“newName”);.getId updatedInstance.setId (response.getBody () ());String resourceUrl =fooResourceUrl + '/' + response.getBody().getId();创建restTemplate。执行(resourceUrl HttpMethod。把,requestCallback(updatedInstance), clientHttpResponse -> null);
8.使用DELETE删除资源
要删除现有的Resource,我们将快速使用delete ()API:
String entityUrl = fooResourceUrl +“/”+ existingResource.getId();restTemplate.delete (entityUrl);
9.配置超时
我们可以配置创建RestTemplate通过简单的使用来超时ClientHttpRequestFactory:
RestTemplate RestTemplate = new RestTemplate(getClientHttpRequestFactory());private ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 5000;HttpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();clientHttpRequestFactory.setConnectTimeout(超时);返回clientHttpRequestFactory;}
我们可以使用HttpClient有关进一步的配置选项:
private ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout = 5000;RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout) .build();CloseableHttpClient client = HttpClientBuilder .create() .setDefaultRequestConfig(config) .build();返回新HttpComponentsClientHttpRequestFactory(客户端);}
10.结论
在本文中,我们介绍了主要的HTTP动词,使用创建RestTemplate使用所有这些来编排请求。
如果您想深入了解如何使用模板进行身份验证,请查看我们的文章使用RestTemplate进行基本验证。
可以找到所有这些示例和代码片段的实现在GitHub。