(資料圖片)

創(chuàng)建請求

創(chuàng)建請求頭:

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

創(chuàng)建請求體:

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

創(chuàng)建請求方式:

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

POST請求

restTemplate發(fā)送POST請求時可以通過如下方法獲取ResponseEntity

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

或用以下方法獲取jsonObject

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

GET請求

GET請求沒有相應(yīng)的方法,只能用exchange方法獲取ResponseEntity

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

若出現(xiàn)如下報錯:

Not enough variables available to expand

則是因為RestTemplate認為大括號{}為占位符,需要將請求頭中的{userId:101,userName:userName}改為{\"userId\":\"101\",\"userName\":\"userName\"}