searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Java中restTemplate携带Header请求

2023-06-12 08:28:26
5
0

创建请求

创建请求头:

Map<String, String> 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<Map<String, String>> 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<JSONObject> 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条评论
0 / 1000
代码的路
100文章数
1粉丝数
代码的路
100 文章 | 1 粉丝
代码的路
100文章数
1粉丝数
代码的路
100 文章 | 1 粉丝
原创

Java中restTemplate携带Header请求

2023-06-12 08:28:26
5
0

创建请求

创建请求头:

Map<String, String> 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<Map<String, String>> 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<JSONObject> 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\"}

 

 

 

文章来自个人专栏
Java开发
31 文章 | 1 订阅
0条评论
0 / 1000
请输入你的评论
0
0