SpringBoot RestTemplate GET POST请求的实例讲解
一)RestTemplate简介
RestTemplate是HTTP客户端库提供了一个更高水平的API。主要用于Rest服务调用。
RestTemplate方法:
getForObject
通过GET检索表示形式。
getForEntity
ResponseEntity通过使用GET检索(即状态,标头和正文)。
headForHeaders
通过使用HEAD检索资源的所有标头。
postForLocation
通过使用POST创建新资源,并Location从响应中返回标头。
postForObject
通过使用POST创建新资源,并从响应中返回表示形式。
postForEntity
通过使用POST创建新资源,并从响应中返回表示形式。
put
通过使用PUT创建或更新资源。
patchForObject
通过使用PATCH更新资源,并从响应中返回表示形式。请注意,JDKHttpURLConnection不支持PATCH,但是ApacheHttpComponents和其他支持。
delete
使用DELETE删除指定URI处的资源。
optionsForAllow
通过使用ALLOW检索资源的允许的HTTP方法。
exchange
前述方法的通用性强(且意见少的版本),在需要时提供了额外的灵活性。它接受RequestEntity(包括HTTP方法,URL,标头和正文作为输入)并返回ResponseEntity。
这些方法允许使用ParameterizedTypeReference而不是Class使用泛型来指定响应类型。
execute
执行请求的最通用方法,完全控制通过回调接口进行的请求准备和响应提取。
二)RestTemplate案例
第一步:创建一个maven项目,在pom.xml引入一个springboot的版本
pom.xml内容:
4.0.0 com.oysept spring_resttemplate 0.0.1-SNAPSHOT jar org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin com.oysept.RestTemplateApplication org.apache.tomcat.maven tomcat7-maven-plugin
application.yml配置:该配置就一个默认端口
server:
port:8080
创建一个springboot启动类RestTemplateApplication
packagecom.oysept;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.boot.builder.SpringApplicationBuilder;
@SpringBootApplication
publicclassRestTemplateApplication{
publicstaticvoidmain(String[]args){
newSpringApplicationBuilder(RestTemplateApplication.class).run(args);
}
}
到此步骤时,可以先运行RestTemplateApplication中的main方法,检验springboot启动是否正常。
第二步:创建一个RestTemplate配置类并注入,因为在使用时,不提前注入ResttTemplate,在通过@Autowired使用会报RestTemplate找不到
packagecom.oysept.config;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.web.client.RestTemplate;
/**
*注册一个RestTemplateBean,否则直接通过@Autowired使用会报RestTemplate找不到
*@authorouyangjun
*/
@Configuration
publicclassRestTemplateConfig{
/**
*方式一:默认是使用JDK原生java.net.HttpURLConnection请求
*@return
*/
@Bean(name="restTemplate")
publicRestTemplaterestTemplate(){
returnnewRestTemplate();
}
/**
*方式二:使用apachehttp内置请求,需要在pom.xml中引入相应的apachejar
*可以使用HttpClient,设置一些http连接池等信息
*@return
*
@Bean(name="restTemplate")
publicRestTemplaterestTemplate(){
returnnewRestTemplate(newHttpComponentsClientHttpRequestFactory());
}
*/
/**
*方式三:使用OkHttp内置请求,需要在pom.xml中引入相应的OkHttp3jar
*可以使用OkHttpClient,设置一些http连接池信息
*@return
*
@Bean(name="restTemplate")
publicRestTemplaterestTemplate(){
returnnewRestTemplate(newOkHttp3ClientHttpRequestFactory());
}
*/
}
第三步:创建一个VO类,用于测试入参和出参
packagecom.oysept.vo;
publicclassMsgVO{
privateStringmsgKey;
privateStringmsgValue;
publicStringgetMsgKey(){returnmsgKey;}
publicvoidsetMsgKey(StringmsgKey){this.msgKey=msgKey;}
publicStringgetMsgValue(){returnmsgValue;}
publicvoidsetMsgValue(StringmsgValue){this.msgValue=msgValue;}
publicStringtoString(){
return"MsgVO[msgKey:"+this.msgKey+",msgValue:"+this.msgValue+"]";
}
}
第四步:创建一个服务端接口,用于测试
packagecom.oysept.controller;
importjava.util.ArrayList;
importjava.util.List;
importorg.springframework.http.MediaType;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestBody;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importcom.oysept.vo.MsgVO;
/**
*服务端,提供接口被调用
*@authorouyangjun
*/
@RestController
publicclassServerController{
//无参GET请求:http://localhost:8080/server/get
@RequestMapping(value="/server/get",method=RequestMethod.GET)
publicStringget(){
return"/server/get";
}
//带参GET请求:http://localhost:8080/server/get/param?param=111222333444
@RequestMapping(value="/server/get/param",method=RequestMethod.GET)
publicStringgetParam(@RequestParam(value="param")Stringparam){
return"/server/get/param,"+param;
}
//路径中带参GET请求:http://localhost:8080/server/get/url/AAAA/BBBB
@RequestMapping(value="/server/get/url/{one}/{two}",method=RequestMethod.GET)
publicStringgetUrl(@PathVariable("one")Stringone,@PathVariable("two")Stringtwo){
return"/get/url/{one}/{two},"+one+","+two;
}
//无参GET请求,返回List:http://localhost:8080/server/get/list
@RequestMapping(value="/server/get/list",method=RequestMethod.GET)
publicList
第五步:创建一个测试服务端接口的API
import的类和注入的RestTemplate:
packagecom.oysept.controller;
importjava.net.URI;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.http.HttpEntity;
importorg.springframework.http.HttpHeaders;
importorg.springframework.http.MediaType;
importorg.springframework.http.RequestEntity;
importorg.springframework.http.ResponseEntity;
importorg.springframework.util.LinkedMultiValueMap;
importorg.springframework.util.MultiValueMap;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.client.RestTemplate;
importorg.springframework.web.util.UriComponentsBuilder;
importcom.oysept.vo.MsgVO;
/**
*客户端,调用服务端提供的接口
*@authorouyangjun
*/
@RestController
publicclassClientController{
//使用默认请求方式
@Autowired
@Qualifier(value="restTemplate")
privateRestTemplaterestTemplate;
//在此处添加客户端测试代码
}
1、GET请求
//直接在浏览中输入访问地址:http://localhost:8080/client/get
@RequestMapping(value="/client/get",method=RequestMethod.GET)
publicStringget(){
//无参GET请求
Stringget=restTemplate.getForObject("http://localhost:8080/server/get",String.class);
System.out.println("==>/server/getreturn:"+get);
//带参GET请求
StringgetParam=restTemplate.getForObject("http://localhost:8080/server/get/param?param=111222333444",String.class);
System.out.println("==>/server/get/paramreturn:"+getParam);
//带参GETurl请求
StringgetUrlParam=restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}",String.class,"AAAA","BBBB");
System.out.println("==>/server/get/url/{one}/{two}return:"+getUrlParam);
//带参GETurl请求
Mapvars=newHashMap();
vars.put("one","HHHH");
vars.put("two","EEEE");
StringgetUrlVars=restTemplate.getForObject("http://localhost:8080/server/get/url/{one}/{two}",String.class,vars);
System.out.println("==>/server/get/url/{one}/{two}return:"+getUrlVars);
//无参GET请求,返回List
@SuppressWarnings("unchecked")
ListgetList=restTemplate.getForObject("http://localhost:8080/server/get/list",List.class);
System.out.println("==>/server/get/listreturn:"+getList);
//GET请求,返回对象
ResponseEntityentity=restTemplate.getForEntity("http://localhost:8080/server/get/MsgVO",MsgVO.class);
System.out.println("==>/server/get/listreturn:"+entity.getBody());
return"GETSUCCESS";
}
2、GETurl中传参请求
//直接在浏览中输入访问地址:http://localhost:8080/client/get/request
//GET请求,url参数,在表头中添加参数
@RequestMapping(value="/client/get/request",method=RequestMethod.GET)
publicStringgetRequest(){
//url中参数
Mapvars=newHashMap();
vars.put("one","HHHH");
vars.put("two","EEEE");
//请求地址
StringuriTemplate="http://localhost:8080/server/get/url/{one}/{two}";
//给URL地址encode转码
URIuri=UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(vars).toUri();
//GET请求参数
RequestEntityrequestEntity=
RequestEntity.get(uri)
.header("MyHeader","aaabbbcccddd")
.build();
//响应
ResponseEntityresponse=restTemplate.exchange(requestEntity,String.class);
//结果
System.out.println("==>/get/requestheader:"+response.getHeaders().getFirst("MyHeader"));
System.out.println("==>/get/requestbody:"+response.getBody());
return"POSTSUCCESS";
}
3、POSTapplication/x-www-form-urlencoded表单传参请求
//直接在浏览中输入访问地址:http://localhost:8080/client/postForm
//POST请求,form表单入参
@RequestMapping(value="/client/postForm",method=RequestMethod.GET)
publicStringpostForm(){
//uri
StringuriTemplate="http://localhost:8080/server/post/form";
//设置请求头为form形式:application/x-www-form-urlencoded
HttpHeadersheaders=newHttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//设置参数,和MsgVO中变量名对应
MultiValueMapmap=newLinkedMultiValueMap();
map.add("msgKey","1234");
map.add("msgValue","TestTest");
//封装请求参数
HttpEntity>requestb=newHttpEntity>(map,
headers);
ResponseEntityresponse=restTemplate.postForEntity(uriTemplate,requestb,String.class);
System.out.println("==>/server/post/formreturn:"+response.getBody());
return"POSTSUCCESS";
}
4、POSTapplication/jsonJSON传参请求
//直接在浏览中输入访问地址:http://localhost:8080/client/postJson
//POST请求,JSON入参
@RequestMapping(value="/client/postJson",method=RequestMethod.GET)
publicStringpostJson(){
//json入参
MsgVOvo=newMsgVO();
vo.setMsgKey("TTT");
vo.setMsgValue("KKK");
StringuriTemplate="http://localhost:8080/server/post/json";
URIuri=UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand().toUri();
RequestEntityrequestEntity=
RequestEntity.post(uri)
.header("Content-Type","application/json;charset=UTF-8")
.body(vo);
ResponseEntityresponse=restTemplate.exchange(requestEntity,MsgVO.class);
System.out.println("==>/server/post/jsonreturn:"+response.getBody());
return"POSTSUCCESS";
}
项目结构图:
以上这篇SpringBootRestTemplateGETPOST请求的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。