java中RestTemplate运用

本文详细介绍了在Java中使用RestTemplate进行HTTP请求的三种方式:postForObject、postForEntity和exchange。对比了它们之间的差异,如postForEntity可以设置header,exchange则能自定义请求方法。同时,指出了在POST请求中设置特定headers可能导致后台无法接收到参数的问题,以及GET请求参数应附加在URL上的注意事项。

请求分为三种类型

以POST请求为例

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

请求代码

private RestTemplate restTemplate = new RestTemplate();

public static void postOne(String url) throws IOException {
    MultiValueMap<String, Object> 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<String, Object> paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id","11111111111");
    HttpEntity<MultiValueMap<String, Object>> 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<String, Object> paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id","11111111111");
    HttpEntity<MultiValueMap<String, Object>> 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<String, Object> paramMap = new LinkedMultiValueMap<>();
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
    url+="?id=111111";
    restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值