創建請(qing)求
創建請求頭:
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}");
創建(jian)請(qing)求方式:
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(requestHeader);
RestTemplate restTemplate = new RestTemplate();
POST請求
restTemplate發送POST請(qing)求時可(ke)以通過(guo)如(ru)下(xia)方法(fa)獲取ResponseEntity:
ResponseEntity responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
或(huo)用以下方法獲(huo)取jsonObject:
JSONObject jsonObject = restTemplate.postForObject(url, httpEntity, JSONObject.class);
GET請求
GET請求沒有相應的方(fang)法(fa),只能用exchange方(fang)法(fa)獲取ResponseEntity:
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class, requestBody);
若出現(xian)如下報錯:
Not enough variables available to expand
則是(shi)因為(wei)RestTemplate認(ren)為(wei)大括號(hao){}為(wei)占位符,需(xu)要將請(qing)求頭中(zhong)的{userId:101,userName:userName}改為{\"userId\":\"101\",\"userName\":\"userName\"}