创建请求
创建请求头:
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\"}
学习更多编程知识,请关注我的公众号:
代码的路
评论