restTemplate發(fā)送POST請(qǐng)求時(shí)可以通過如下方法獲取ResponseEntity:
(資料圖片)
創(chuàng)建請(qǐng)求
創(chuàng)建請(qǐng)求頭:
Map requestBody = new HashMap<>();requestBody.put("userId", userId);requestBody.put("userName", userName);
創(chuàng)建請(qǐng)求體:
HttpHeaders requestHeader = new HttpHeaders();requestHeader.add("cookie", "cookie");requestHeader.add("userInfo", "{userId:101,userName:userName}");
創(chuàng)建請(qǐng)求方式:
HttpEntity
POST請(qǐng)求
restTemplate發(fā)送POST請(qǐng)求時(shí)可以通過如下方法獲取ResponseEntity
:
ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
或用以下方法獲取jsonObject
:
JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);
GET請(qǐng)求
GET請(qǐng)求沒有相應(yīng)的方法,只能用exchange方法獲取ResponseEntity
:
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class, requestBody);
若出現(xiàn)如下報(bào)錯(cuò):
Not enough variables available to expand
則是因?yàn)镽estTemplate認(rèn)為大括號(hào){}為占位符,需要將請(qǐng)求頭中的{userId:101,userName:userName}
改為{\"userId\":\"101\",\"userName\":\"userName\"}
關(guān)鍵詞: