当前位置:网站首页>Resttemplate usage details and pit stepping records
Resttemplate usage details and pit stepping records
2022-06-09 11:57:00 【sunnyday0426】
1.1 sketch
Need to use... In recent projects http Third party services are called in the form of , What we use in our project is RestTemplate Make interactive calls . Unlike what we used to write HttpClient, Need to write a lot of tool classes ,RestTemplate It's basically out of the box , This article mainly introduces its application in spring boot Basic projects in use , For daily development, etc , Basically, there is no problem .
1.1.1 Rest
When talking about REST when , A common mistake is to think of it as “ be based on URL Of Web service ”—— take REST As another type of remote procedure call (remote procedure call,RPC) Mechanism , It's like SOAP equally , It's just a simple HTTP URL To trigger , Instead of using SOAP a large number of XML Namespace
On the contrary ,REST And RPC Almost nothing .RPC It's service-oriented , And focus on actions and actions ; and REST It's resource oriented , Emphasize things and terms that describe an application .
More succinctly ,REST Is to transfer the state of resources from the server to the client in the form most suitable for the client or server ( Or vice versa ).
stay REST in , Resources through URL Identify and locate . as for RESTful URL There are no strict rules in the structure of , however URL Should be able to identify resources , Instead of simply sending a command to the server . Again , The core of attention is things , Not behavior .
1.1.2 Spring How to use Rest resources
With the help of RestTemplate,Spring Applications are easy to use REST resources Spring Of RestTemplate Access design patterns that use the template method
The template method delegates the part of the process related to a specific implementation to the interface , And different implementations of this interface define different behaviors of the interface
RestTemplate Defined 36 One and REST How resources interact , Most of them correspond to HTTP Methods .
Actually , There's only 11 An independent method , Ten of them have three overload forms , The eleventh is overloaded six times , In this way, a total of 36 A way .
delete()
In particularURLExecute... On resourcesHTTP DELETEoperationexchange()
stayURLTo execute specificHTTPMethod , Returns the... Containing the objectResponseEntity, This object is mapped from the response bodyexecute()
stayURLTo execute specificHTTPMethod , Returns an object from the response body mapgetForEntity()
Send aHTTP GETrequest , Back toResponseEntityContains the objects mapped by the response bodygetForObject()
Send aHTTP GETrequest , The returned request body will be mapped to an objectpostForEntity()POSTData to aURL, Returns... That contains an objectResponseEntity, This object is mapped from the response bodypostForObject()POSTData to aURL, Returns the object formed by matching the response bodyheadForHeaders()
send outHTTP HEADrequest , Return contains specific resourcesURLOfHTTPheadoptionsForAllow()
send outHTTP OPTIONSrequest , Return to specificURLOfAllowHeader informationpostForLocation()POSTData to aURL, Returns the... Of the newly created resourceURLput()PUTResources to specificURL
actually , because Post The non idempotent nature of the operation , It can almost replace other CRUD operation
1.2 Get request
RestTemplate Of get There are several methods above , It can be divided into two categories : getForEntity() and getForObject()
First of all to see getForEntity() Return value type of ResponseEntity
<T> ResponseEntity<T> getForEntity()
to glance at ResponseEntity The document description of :
You can see It inherited HttpEntity, Encapsulates the returned response information , Include Response state , Response head and Response body
Before testing, we first Create a Rest service , The simulation provides Rest data , Here is given Controller Layer code :
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "getAll")
public List<UserEntity> getUser() {
List<UserEntity> list = userService.getAll();
return list;
}
@RequestMapping("get/{id}")
public UserEntity getById(@PathVariable(name = "id") String id) {
return userService.getById(id);
}
@RequestMapping(value = "save")
public String save(UserEntity userEntity) {
return " Saved successfully ";
}
@RequestMapping(value = "saveByType/{type}")
public String saveByType(UserEntity userEntity,@PathVariable("type")String type) {
return " Saved successfully ,type="+type;
}
}
1.2.1 test : getForEntity
No parameters getForEntity Method
@RequestMapping("getForEntity")
public List<UserEntity> getAll2() {
ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost/getAll", List.class);
HttpHeaders headers = responseEntity.getHeaders();
HttpStatus statusCode = responseEntity.getStatusCode();
int code = statusCode.value();
List<UserEntity> list = responseEntity.getBody();
System.out.println(list.toString());
return list;
}
Parametric getForEntity request , parameter list , have access to {} Conduct url Path placeholder
// Parametric getForEntity request , parameter list
@RequestMapping("getForEntity/{id}")
public UserEntity getById2(@PathVariable(name = "id") String id) {
ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, id);
UserEntity userEntity = responseEntity.getBody();
return userEntity;
}
Parametric get request , Use map Package parameters
// Parametric get request , Use map Package parameters
@RequestMapping("getForEntity/{id}")
public UserEntity getById4(@PathVariable(name = "id") String id) {
HashMap<String, String> map = new HashMap<>();
map.put("id",id);
ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost/get/{id}", UserEntity.class, map);
UserEntity userEntity = responseEntity.getBody();
return userEntity;
}
So we can get Http All requested information .
however , Usually we don't want to Http All requested information , Just need the corresponding body , In this case ,RestTemplate Provides getForObject() Method is used to get only Response body information getForObject and getForEntity The usage is almost the same , Indicates that the return value returns Response body , Save us Go again getBody()
1.2.2 test : getForObject
No parameters getForObject request
// No parameters getForObject request
@RequestMapping("getAll2")
public List<UserEntity> getAll() {
List<UserEntity> list = restTemplate.getForObject("http://localhost/getAll", List.class);
System.out.println(list.toString());
return list;
}
Parametric getForObject request , Use the parameter list
// Parametric getForObject request
@RequestMapping("get2/{id}")
public UserEntity getById(@PathVariable(name = "id") String id) {
UserEntity userEntity = restTemplate.getForObject("http://localhost/get/{id}", UserEntity.class, id);
return userEntity;
}
Parametric get request , Use map Encapsulate request parameters
// Parametric get request , Use map Encapsulate request parameters
@RequestMapping("get3/{id}")
public UserEntity getById3(@PathVariable(name = "id") String id) {
HashMap<String, String> map = new HashMap<>();
map.put("id",id);
UserEntity userEntity = restTemplate.getForObject("http://localhost/get/{id}", UserEntity.class, map);
return userEntity;
}
1.3 Post request
I understand get After the request ,Post The request becomes very simple , We can see post There are the following methods :
1.3.1 test :postForEntity
post request , preservation UserEntity Antithetic image
//post request , Submit UserEntity Antithetic image
@RequestMapping("saveUser")
public String save(UserEntity userEntity) {
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/save", userEntity, String.class);
String body = responseEntity.getBody();
return body;
}
Browser access : http://localhost/saveUser?username=itguang&password=123456&age=20&[email protected]
Let's debug again , see responseEntity Information in
Parametric postForEntity request
// Parametric postForEntity request
@RequestMapping("saveUserByType/{type}")
public String save2(UserEntity userEntity,@PathVariable("type")String type) {
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class, type);
String body = responseEntity.getBody();
return body;
}
// Parametric postForEntity request , Use map encapsulation
@RequestMapping("saveUserByType2/{type}")
public String save3(UserEntity userEntity,@PathVariable("type")String type) {
HashMap<String, String> map = new HashMap<>();
map.put("type", type);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class,map);
String body = responseEntity.getBody();
return body;
}
Our browser access : localhost/saveUserByType/120?username=itguang&password=123456&age=20&[email protected]
It will return : Saved successfully ,type=120
With other request methods , Due to infrequent use , So I won't talk about
1.4 Record on pit :restTemplate Of exchange Method get Ask for the newspaper 400 Bad request【restTemplate Bug】 Solutions for
1.4.1 Filling record
The following code ,url=http://www.baidu.com Time request message 400
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", authorization);
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
if (map != null) {
map.forEach((k, v) -> {
if (StringUtils.isNotBlank(v)) {
requestBody.add(k,v);
}
});
}
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
try {
ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
return new HttpResDTO(res.getStatusCodeValue(), res.getBody());
} catch (HttpClientErrorException ex) {
log.error("rest template for face exception, error code: {}, error message: {}", ex.getRawStatusCode(), ex.getMessage());
return new HttpResDTO(ex.getRawStatusCode(), ex.getResponseBodyAsString());
} catch (UnknownHttpStatusCodeException e) {
String responseBodyAsString = e.getResponseBodyAsString();
log.warn("UnknownHttpStatusCodeException:{}",responseBodyAsString);
JSONObject parse = JSONObject.parseObject(responseBodyAsString);
throw new RuntimeException(parse.get("message").toString());
}
1.4.2 Solution
get Request directly in url Upper spelling parameters , Such as ?type=1&name=xxString uri =tempUrl + “?keys={keys}”; adopt map Pass on keys
Map<String, String> map = new HashMap<>(1);
map.put(“keys”, “xdfdf”);
ResponseEntity res = restTemplate.getForEntity(url, String.class, map);
边栏推荐
- How to insert the video monitoring memory card into the Yuntai pro of Xiaomi smart camera
- 05 | D4 model: overview of China Taiwan planning and construction methodology
- No remote desktop license server can provide licenses
- H3C certified cloud computing Engineer
- [data center stage] 00 opening words data center stage, is it a trap? Or the golden key?
- iphone5s显示被停用了解决办法
- Win7系统怎么卸载IE浏览器
- 04 | everything must be done in advance: four issues that must be clearly considered before the construction of China Taiwan Relations
- 2022年软考高级网络规划设计师备考指南
- Apple claims that M2 is 26 times stronger than Intel i5. The truth of false marketing has been revealed!
猜你喜欢

8.<tag-回溯和全排列>lt.46. 全排列 + lt.47. 全排列 II

Prompt credssp encryption database correction when windows is remote

4.<tag-回溯和组合及其剪枝>lt.39.组合总和 + lt.40. 组合总和 II dbc

Win10 your organization has turned off automatic update. How to solve the problem?

7. remove elements

Security evaluation of commercial password application

Use of component El scrollbar

【转载】搞懂G1垃圾收集器

6. exchange the nodes in the linked list in pairs

7.移除元素
随机推荐
使用 KubeKey 搭建 Kubernetes/KubeSphere 环境的'心路(累)历程'
go-zero 微服务实战系列(二、服务拆分)
05 | D4 model: overview of China Taiwan planning and construction methodology
【数据中台】00丨开篇词丨数据中台,是陷阱?还是金钥匙?
Go zero micro Service Practice Series (II. Service splitting)
你的微服务敢独立交付么?
Focus on DNS: analysis of ISC bind
07 | the second step of the mid platform landing: enterprise digital panoramic planning (define)
8K分辨率7680*4320
H3C Certified Safety Technology Senior Engineer
H3C认证网络工程师
使用U盘一比一拷贝核心板系统镜像的方法
从2022年的这几篇论文看推荐系统序列建模的趋势
Simple use of GDB
R语言使用MatchIt包进行倾向性匹配分析、使用match.data函数构建匹配后的样本集合、通过分析不同分组对应的协变量的均值来判断倾向性评分匹配后样本中的所有协变量的平衡情况
R语言party包ctree函数构建条件推理决策树(Conditional inference trees)、使用plot函数可视化训练好的条件推理决策树
【直播回顾】Hello HarmonyOS应用篇第六课——短视频应用开发
8.<tag-回溯和全排列>lt.46. 全排列 + lt.47. 全排列 II
How to model 3DMAX (I)
How to make money through Hongmeng ecology?