一)RestTemplate简介
RestTemplate是HTTP客户端库提供了一个更高水平的API。主要用于Rest服务调用。
RestTemplate方法:
方法组 描述getForObject
通过GET检索表示形式。
getForEntity
ResponseEntity通过使用GET 检索(即状态,标头和正文)。
headForHeaders
通过使用HEAD检索资源的所有标头。
postForLocation
通过使用POST创建新资源,并Location从响应中返回标头。
postForObject
通过使用POST创建新资源,并从响应中返回表示形式。
postForEntity
通过使用POST创建新资源,并从响应中返回表示形式。
put
通过使用PUT创建或更新资源。
patchForObject
通过使用PATCH更新资源,并从响应中返回表示形式。请注意,JDK HttpURLConnection不支持PATCH,但是Apache HttpComponents和其他支持。
delete
使用DELETE删除指定URI处的资源。
optionsForAllow
通过使用ALLOW检索资源的允许的HTTP方法。
exchange
前述方法的通用性强(且意见少的版本),在需要时提供了额外的灵活性。它接受RequestEntity(包括HTTP方法,URL,标头和正文作为输入)并返回ResponseEntity。
这些方法允许使用ParameterizedTypeReference而不是Class使用泛型来指定响应类型。
execute
执行请求的最通用方法,完全控制通过回调接口进行的请求准备和响应提取。
二)RestTemplate案例
第一步:创建一个maven项目,在pom.xml引入一个springboot的版本
pom.xml内容:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://ponentsBuilder.fromUriString(uriTemplate).buildAndExpand().toUri(); RequestEntity<MsgVO> requestEntity = RequestEntity.post(uri) .header("Content-Type", "application/json; charset=UTF-8") .body(vo); ResponseEntity<MsgVO> response = restTemplate.exchange(requestEntity, MsgVO.class); System.out.println("==>/server/post/json return: " + response.getBody()); return "POST SUCCESS";}项目结构图:
以上这篇SpringBoot RestTemplate GET POST请求的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。