关于java:Java中restTemplate携带Header请求

39次阅读

共计 988 个字符,预计需要花费 3 分钟才能阅读完成。

创立申请

创立申请头:

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