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);
    		```
  • 相关阅读:
    JDK中Unsafe类详解
    JAVA并发理论与实践
    关于FastJSON
    指数退避算法
    MySQL多表关联查询效率高点还是多次单表查询效率高,为什么?
    App开放接口api安全性—Token签名sign的设计与实现
    使用Jmeter进行http接口性能测试
    短信验证登录实现流程
    使用 Postman 取得 Token 打另一隻 API
    SpringMVC拦截器HandlerInterceptor使用
  • 原文地址:https://www.cnblogs.com/mikemhm/p/12167538.html
Copyright © 2011-2022 走看看