当前位置:网站首页>RestTemplate 使用:设置请求头、请求体
RestTemplate 使用:设置请求头、请求体
2022-08-02 12:49:00 【良月生秋】
文章目录
HttpEntity
使用 RestTemplate 时可以通过 HttpEntity 设置请求头和请求体。HttpEntity 有4个构造方法:
- 既不设置请求体,也不设置请求头
- 只设置请求体
- 只设置请求头
- 同时设置请求体和请求头
HttpEntity 源码:
/**
* Create a new, empty {@code HttpEntity}.
*/
protected HttpEntity() {
this(null, null);
}
/**
* Create a new {@code HttpEntity} with the given body and no headers.
* @param body the entity body
*/
public HttpEntity(T body) { // 只设置请求体
this(body, null);
}
/**
* Create a new {@code HttpEntity} with the given headers and no body.
* @param headers the entity headers
*/
public HttpEntity(MultiValueMap<String, String> headers) { // 只设置请求头
this(null, headers);
}
/**
* Create a new {@code HttpEntity} with the given body and headers.
* @param body the entity body
* @param headers the entity headers
*/
public HttpEntity(T body, MultiValueMap<String, String> headers) { // 同时设置请求体与请求头
this.body = body;
HttpHeaders tempHeaders = new HttpHeaders();
if (headers != null) {
tempHeaders.putAll(headers);
}
this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}
1、为 post、put 请求设置请求头、请求体
如果是为 post、put 请求设置请求头、请求体,可以在调用方法时,利用第二个参数传入 HttpEntity 对象,例如:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
Book book = restTemplate.postForObject("http://127.0.0.1:8080/getbook", requestEntity, Book.class);
PS:public class HttpHeaders implements MultiValueMap<String, String>, Serializable
同时设置请求头和请求体:
@PostMapping("post_with_body_and_header")
public void postWithBodyAndHeader(@RequestBody(required = false) UserEntity requestBody) {
// 1.请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("headerName1", "headerValue1");
httpHeaders.add("headerName2", "headerValue2");
httpHeaders.add("headerName3", "headerValue3");
httpHeaders.add("Content-Type", "application/json"); // 传递请求体时必须设置
// 2.请求头 & 请求体
HttpEntity<String> fromEntity = new HttpEntity<>(JSONUtil.toJsonStr(requestBody), httpHeaders);
MessageBox responseBody = restTemplate.postForObject(INVOKE_URL + "/test/receive", fromEntity, MessageBox.class);
log.info("响应体:{}", JSONUtil.toJsonPrettyStr(responseBody));
}
2、为其他请求设置请求头、请求体
如果是其它HTTP方法调用要设置请求头,可以使用exchange()方法:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyRequestHeader", "MyValue");
HttpEntity requestEntity = new HttpEntity(requestHeaders);
HttpEntity<String> response = template.exchange(
"http://example.com/hotels/{hotel}",
HttpMethod.GET,
requestEntity,
String.class,
"42"
);
String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
String body = response.getBody();
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
- PGSQL database to realize the import and export
- 消除气泡解救蘑菇h5小游戏源码
- kvm部署
- How to set up wireless PPI communication between Weiluntong touch screen and S7-200smart?
- 智能图像分析-智能家用电器图像目标检测统计计数检测与识别-艾科瑞特科技(iCREDIT)
- 图论之Floyd,多源图最短路如何暴力美学?
- Wireless vibrating wire acquisition instrument remote modification method
- 工厂方法模式
- FreeRTOS--stack experiment
- LeetCode_139_单词拆分
猜你喜欢
js semi-circle loading progress animation js special effects
GCC版本升级到指定版本
SQL Server database generation and execution of SQL scripts
np.nan, np.isnan, None, pd.isnull, pd.isna finishing and summary
MD5 detailed explanation (check file integrity)
MyCat2 introduction and installation and basic use
np.nan, np.isnan, None, pd.isnull, pd.isna 整理与小结
LeetCode_377_组合总和Ⅳ
Custom mvc framework review
FreeRTOS--优先级实验
随机推荐
Four seasons of trees realized by svg
Process finished with exit code 1
SQL Server 2014 installation tutorial (nanny-level graphic tutorial)
js真3d柱状图插件
How to turn off hardware acceleration [easy to understand]
SQL Server修改数据
无线振弦采集仪远程修改参数方式
qt 编译报错 No rule to make target
svg balloon rises explosion js special effect
30行代码实现无服务器实时健康码识别--操作手册
数据湖(二):什么是Hudi
【第六届强网杯CTF-Wp】
设置代理服务器(谷歌+IE)「建议收藏」
Chapter 11 Documents
svg实现的树木四季变化
PGSQL database to realize the import and export
0801~ Interview questions
单例模式的七种写法,你都知道吗?
Openlayers 快速上手教程
js stopwatch countdown plugin