Java中restTemplate携带Header请求

时间:2023-03-23 21:22:51


(资料图片仅供参考)

创建请求

创建请求头:

Map requestBody = new HashMap<>();requestBody.put("userId", userId);requestBody.put("userName", userName);

创建请求体:

HttpHeaders requestHeader = new HttpHeaders();requestHeader.add("cookie", "cookie");requestHeader.add("userInfo", "{userId:101,userName:userName}");

创建请求方式:

HttpEntity> httpEntity = new HttpEntity<>(requestHeader);RestTemplate restTemplate = new RestTemplate();

POST请求

restTemplate发送POST请求时可以通过如下方法获取ResponseEntity

ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);

或用以下方法获取jsonObject

JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);

GET请求

GET请求没有相应的方法,只能用exchange方法获取ResponseEntity

ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class, requestBody);

若出现如下报错:

Not enough variables available to expand

则是因为RestTemplate认为大括号{}为占位符,需要将请求头中的{userId:101,userName:userName}改为{\"userId\":\"101\",\"userName\":\"userName\"}

标签:

来源:腾讯云
0
上一篇: 下一篇:

最近更新

  Copyright @ 2001-2013 www.caixunnews.com All Rights Reserved 财经新闻网 版权所有 京ICP备12018864号-1

  网站所登新闻、资讯等内容, 均为相关单位具有著作权,转载请注明出处

  未经彩迅新闻网书面授权,请勿建立镜像 联系我们:  291 32 36@qq.com

营业执照公示信息