SpringBootRestTemplateGETPOST请求的实例讲解
⼀)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项⽬,在l引⼊⼀个springboot的版本
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>
<groupId&sept</groupId>
<artifactId>spring_resttemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass&sept.RestTemplateApplication</mainClass>
</configuration>
</plugin>
<plugin>
<groupId>at.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
server:
port: 8080
创建⼀个springboot启动类RestTemplateApplication
sept;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(RestTemplateApplication.class).run(args);
}
}
到此步骤时,可以先运⾏RestTemplateApplication中的main⽅法,检验springboot启动是否正常。
第⼆步:创建⼀个RestTemplate配置类并注⼊,因为在使⽤时,不提前注⼊ResttTemplate,在通过@Autowired使⽤会报RestTemplate不到
fig;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* 注册⼀个RestTemplate Bean, 否则直接通过@Autowired使⽤会报RestTemplate不到 * @author ouyangjun
*/
@Configuration
public class RestTemplateConfig {
/**
* ⽅式⼀: 默认是使⽤JDK原⽣java.HttpURLConnection请求
* @return
*/
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate();
}
/**
* ⽅式⼆: 使⽤apache http内置请求, 需要在l中引⼊相应的apache jar
* 可以使⽤HttpClient,设置⼀些http连接池等信息
* @return
*
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
*/
/
**
* ⽅式三: 使⽤OkHttp内置请求, 需要在l中引⼊相应的OkHttp3 jar
* 可以使⽤OkHttpClient,设置⼀些http连接池信息
* @return
*
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
*/
}
第三步:创建⼀个VO类,⽤于测试⼊参和出参
sept.vo;
public class MsgVO {
private String msgKey;
private String msgValue;
public String getMsgKey() {return msgKey;}
public void setMsgKey(String msgKey) {this.msgKey = msgKey;}
public String getMsgValue() {return msgValue;}
public void setMsgValue(String msgValue) {this.msgValue = msgValue;}
public String toString() {
return "MsgVO [msgKey: "+this.msgKey+", msgValue: "+this.msgValue+"]";
}
}
第四步:创建⼀个服务端接⼝,⽤于测试
ller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
sept.vo.MsgVO;
/**
* 服务端, 提供接⼝被调⽤
* @author ouyangjun
*/
@RestController
public class ServerController {
// ⽆参GET请求: localhost:8080/server/get
@RequestMapping(value = "/server/get", method = RequestMethod.GET)
public String get() {
return "/server/get";
}
// 带参GET请求: localhost:8080/server/get/param?param=111222333444
@RequestMapping(value = "/server/get/param", method = RequestMethod.GET)
public String getParam(@RequestParam(value = "param") String param) {
return "/server/get/param," + param;
}
// 路径中带参GET请求: localhost:8080/server/get/url/AAAA/BBBB
@RequestMapping(value = "/server/get/url/{one}/{two}", method = RequestMethod.GET)  public String getUrl(@PathVariable("one") String one, @PathVariable("two") String two) {    return "/get/url/{one}/{two}," + one + "," + two;
}
// ⽆参GET请求, 返回List: localhost:8080/server/get/list
@RequestMapping(value = "/server/get/list", method = RequestMethod.GET)
public List<Object> getList() {
List<Object> list = new ArrayList<Object>();
list.add(11);
list.add("AA");
return list;
}
// ⽆参GET请求, 返回对象: localhost:8080/server/get/MsgVO
@RequestMapping(value = "/server/get/MsgVO", method = RequestMethod.GET)
public MsgVO getMsgVO() {
MsgVO vo = new MsgVO();
vo.setMsgKey("keyAAA");
vo.setMsgValue("valueBBB");
return vo;
}
// POST请求, 表单参数, application/x-www-form-urlencoded
@RequestMapping(value = "/server/post/form", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public MsgVO postForm(MsgVO msgVO) {
System.out.println("msgKey: " + MsgKey() + ", msgValue: " + MsgValue());
return msgVO;
}
// POST请求, JSON参数, application/json
@RequestMapping(value = "/server/post/json", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public MsgVO postJson(@RequestBody MsgVO msgVO) {
System.out.println("msgKey: " + MsgKey() + ", msgValue: " + MsgValue());
return msgVO;
}
}
第五步:创建⼀个测试服务端接⼝的API
import的类和注⼊的RestTemplate:
ller;
import java.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
sept.vo.MsgVO;
/
**
* 客户端, 调⽤服务端提供的接⼝
* @author ouyangjun
*/
@RestController
public class ClientController {
// 使⽤默认请求⽅式
@Autowired
@Qualifier(value = "restTemplate")
springframework和springbootprivate RestTemplate restTemplate;
// 在此处添加客户端测试代码
}
1、GET请求
// 直接在浏览中输⼊访问地址: localhost:8080/client/get
@RequestMapping(value = "/client/get", method = RequestMethod.GET)
public String get() {
// ⽆参GET请求
String get = ForObject("localhost:8080/server/get", String.class);
System.out.println("==>/server/get return: " + get);
// 带参GET请求
String getParam = ForObject("localhost:8080/server/get/param?param=111222333444", String.class);
System.out.println("==>/server/get/param return: " + getParam);
// 带参GET url请求
String getUrlParam = ForObject("localhost:8080/server/get/url/{one}/{two}", String.class, "AAAA", "BBBB");  System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlParam);
// 带参GET url请求
Map<String, String> vars = new HashMap<String, String>();
vars.put("one", "HHHH");
vars.put("two", "EEEE");
String getUrlVars = ForObject("localhost:8080/server/get/url/{one}/{two}", String.class, vars);
System.out.println("==>/server/get/url/{one}/{two} return: " + getUrlVars);
// ⽆参GET请求, 返回List
@SuppressWarnings("unchecked")
List<String> getList = ForObject("localhost:8080/server/get/list", List.class);
System.out.println("==>/server/get/list return: " + getList);
// GET请求, 返回对象
ResponseEntity<MsgVO> entity = ForEntity("localhost:8080/server/get/MsgVO", MsgVO.class);
System.out.println("==>/server/get/list return: " + Body());
return "GET SUCCESS";
}
2、GET url中传参请求
// 直接在浏览中输⼊访问地址: localhost:8080/client/get/request
// GET请求, url参数, 在表头中添加参数
@RequestMapping(value = "/client/get/request", method = RequestMethod.GET)
public String getRequest() {
// url中参数
Map<String, String> vars = new HashMap<String, String>();
vars.put("one", "HHHH");
vars.put("two", "EEEE");
// 请求地址
String uriTemplate = "localhost:8080/server/get/url/{one}/{two}";
// 给URL地址encode转码
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(vars).toUri();
// GET请求参数
RequestEntity<Void> requestEntity =
<(uri)
.header("MyHeader", "aaabbbcccddd")
.build();
// 响应
ResponseEntity<String> response = hange(requestEntity, String.class);
// 结果
System.out.println("==>/get/request header: " + Headers().getFirst("MyHeader"));
System.out.println("==>/get/request body: " + Body());
return "POST SUCCESS";
}
3、POST application/x-www-form-urlencoded表单传参请求
// 直接在浏览中输⼊访问地址: localhost:8080/client/postForm
// POST请求, form表单⼊参
@RequestMapping(value = "/client/postForm", method = RequestMethod.GET)
public String postForm() {
// uri
String uriTemplate = "localhost:8080/server/post/form";
// 设置请求头为form形式: application/x-www-form-urlencoded
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 设置参数, 和MsgVO中变量名对应
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("msgKey", "1234");
map.add("msgValue", "TestTest");
// 封装请求参数
HttpEntity<MultiValueMap<String, String>> requestb = new HttpEntity<MultiValueMap<String, String>>(map,
headers);
ResponseEntity<String> response = restTemplate.postForEntity(uriTemplate, requestb, String.class);
System.out.println("==>/server/post/form return: " + Body());
return "POST SUCCESS";
}
4、POST application/json JSON传参请求
// 直接在浏览中输⼊访问地址: localhost:8080/client/postJson
// POST请求, JSON⼊参
@RequestMapping(value = "/client/postJson", method = RequestMethod.GET)
public String postJson() {
// json⼊参
MsgVO vo = new MsgVO();
vo.setMsgKey("TTT");
vo.setMsgValue("KKK");
String uriTemplate = "localhost:8080/server/post/json";
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand().toUri();
RequestEntity<MsgVO> requestEntity =
RequestEntity.post(uri)
.header("Content-Type", "application/json; charset=UTF-8")
.body(vo);
ResponseEntity<MsgVO> response = hange(requestEntity, MsgVO.class);
System.out.println("==>/server/post/json return: " + Body());
return "POST SUCCESS";
}
项⽬结构图:
以上这篇SpringBoot RestTemplate GET POST请求的实例讲解就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。