<强>一)创建RestTemplate简介强>
创建RestTemplate是HTTP客户端库提供了一个更高水平的API。主要用于其他服务调用。
创建RestTemplate方法:
方法组 描述getForObject
通过得到检索表示形式。
getForEntity
ResponseEntity通过使用得到检索(即状态,标头和正文)。
headForHeaders
通过使用头检索资源的所有标头。
postForLocation
通过使用POST创建新资源,并从位置响应中返回标头。
postForObject
通过使用POST创建新资源,并从响应中返回表示形式。
postForEntity
通过使用POST创建新资源,并从响应中返回表示形式。
把
通过使用把创建或更新资源。
patchForObject
通过使用补丁更新资源,并从响应中返回表示形式。请注意,JDK HttpURLConnection不支持补丁,但是Apache HttpComponents和其他支持。
删除
使用删除删除指定URI处的资源。
optionsForAllow
通过使用允许检索资源的允许的HTTP方法。
交换
前述方法的通用性强(且意见少的版本),在需要时提供了额外的灵活性。它接受RequestEntity(包括HTTP方法,URL、标头和正文作为输入)并返回ResponseEntity。
这些方法允许使用ParameterizedTypeReference而不是类使用泛型来指定响应类型。
执行
执行请求的最通用方法,完全控制通过回调接口进行的请求准备和响应提取。
<强>二)创建RestTemplate案例强>
第一步:创建一个maven项目,在pom.xml引入一个springboot的版本
pom.xml内容:
& lt;项目xmlns=" http://maven.apache.org/POM/4.0.0 " xmlns: xsi=" http://www.w3.org/2001/XMLSchema-instance " xsi: schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”比; & lt; modelVersion> 4.0.0 & lt; groupId> com.oysept & lt; artifactId> spring_resttemplate & lt; version> 0.0.1-SNAPSHOT & lt; packaging> jar & lt; parent> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-parent & lt; version> 2.1.4.RELEASE & lt; relativePath/比; & lt;/parent> & lt; dependencies> & lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-web & lt;/dependency> & lt;/dependencies> & lt; build> & lt; plugins> & lt; plugin> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-maven-plugin & lt; configuration> & lt; mainClass> com.oysept.RestTemplateApplication & lt;/configuration> & lt;/plugin> & lt; plugin> & lt; groupId> org.apache.tomcat.maven & lt; artifactId> tomcat7-maven-plugin & lt;/plugin> & lt;/plugins> & lt;/build> & lt;/project>
application.yml配置:该配置就一个默认端口
服务器:
端口:8080 引用>
创建一个springboot启动类RestTemplateApplication
包com.oysept; 进口org.springframework.boot.autoconfigure.SpringBootApplication; 进口org.springframework.boot.builder.SpringApplicationBuilder; @SpringBootApplication 公开课RestTemplateApplication { 公共静态void main (String [] args) { 新SpringApplicationBuilder (RestTemplateApplication.class) .run (args); } }到此步骤时,可以先运行RestTemplateApplication中主要的方法,检验springboot启动是否正常。
SpringBoot创建RestTemplate得到职位请求的实例讲解