zoukankan      html  css  js  c++  java
  • 接口开发中的 RestTemplate 传参问题

    RestTemplate

    在使用 RestTemplate 时,通过map传参,遇到传不了参的问题

    • 对于get请求,必须在请求的url中添加?a={a},参数为对应的map的key
    RestTemplate restTemplate = new RestTemplate();
    		String url = "https://restapi.amap.com/v3/weather/weatherInfo?key={key}&city={city}";
    		Map map = new HashMap();
    		map.put("key","4d6ab733dcfed0e82806b9a97ff602ff");
    		map.put("city","330100");
    
    		JSONObject forObject = restTemplate.getForObject(url, JSONObject.class, map);
    
    • 对于post请求
      1、调用postForObject方法 2、使用postForEntity方法 3、调用exchange方法
      postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。exchange方法和postForEntity类似,但是更灵活,exchange还可以调用get、put、delete请求。使用这三种方法调用post请求传递参数,Map不能定义为以下两种类型(url使用占位符进行参数传递时除外)
    Map<String, Object> paramMap = new HashMap<String, Object>();
    Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
    

    使用MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();可以实现传参

    RestTemplate restTemplate = new RestTemplate();
            // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
            MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
            paramMap.add("token",token);
            String s5 = restTemplate.postForObject(url, paramMap, String.class);
    		```
  • 相关阅读:
    mixin混合
    python类内部调用自己的成员函数必须加self
    合并/取消合并单元格
    pandas 显示所有的行和列
    pandas 利用openpyxl设置表格样式
    Nowcoder9983G.糖果(并查集)
    Nowcoder9983F.匹配串(思维)
    Nowcoder9983E.买礼物(链表+线段树)
    Nowcoder9983C.重力追击(暴力+少用sqrt)
    Nowcoder9983B.内卷(双指针)
  • 原文地址:https://www.cnblogs.com/mikemhm/p/12167538.html
Copyright © 2011-2022 走看看