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);
    		```
  • 相关阅读:
    1、数据加密基础
    cookie——小甜品
    使用SpringBoot开发REST服务
    从编辑距离、BK树到文本纠错
    360影视视频下载
    从Trie树到双数组Trie树
    使用websocket-sharp来创建c#版本的websocket服务
    OFFICE 文档转换为html在线预览
    IDEA+PHP+XDebug调试配置
    HTML5录音控件
  • 原文地址:https://www.cnblogs.com/mikemhm/p/12167538.html
Copyright © 2011-2022 走看看