java中RestTemplate运用

请求分为三种类型

以POST请求为例

  1. 调用postForObject方法
  2. 使用postForEntity方法
  3. 调用exchange方法
  • postForObject和postForEntity方法的区别:postForEntity方法可以设置header的属性。
  • exchange方法和postForEntity区别: exchange可以设置请求方式(如:GET、POST)。
  • 使用这三种方法传递参数,Map不能定义为以下两种类型
    Map paramMap = new HashMap();
    Map paramMap = new LinkedHashMap();
    把Map类型换成LinkedMultiValueMap后,参数成功传递到后台
    MultiValueMap paramMap = new LinkedMultiValueMap();

请求代码

private RestTemplate restTemplate = new RestTemplate();

public static void postOne(String url) throws IOException {
    MultiValueMap paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id","11111111111");
    restTemplate.postForObject(url, paramMap, String.class);
}

public static void postTwo(String url) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    MultiValueMap paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id","11111111111");
    HttpEntity> httpEntity = new HttpEntity<>(paramMap,headers);
    restTemplate.postForEntity(url, httpEntity, String.class);
}

public static void postThree(String url) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("token","adsfghghjjfhfdsaghjds");
    MultiValueMap paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id","11111111111");
    HttpEntity> httpEntity = new HttpEntity<>(paramMap,headers);
    restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
}

注意:post请求方式将headers头做如下设置,后台将区不到参数,未查明原因
headers.setContentType(MediaType.APPLICATION_JSON);

get请求的请求参数需要挂在url上,用参数体传递将去不到数据,例如:

public static void getTest(String url) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    MultiValueMap paramMap = new LinkedMultiValueMap<>();
    HttpEntity> httpEntity = new HttpEntity<>(paramMap,headers);
    url+="?id=111111";
    restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
}

你可能感兴趣的:(java,开发语言,后端)