乐趣区

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

创立申请

创立申请头:

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\"}

 
 

学习更多编程常识,请关注我的公众号:

代码的路

退出移动版