Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑

当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑

1 POST传递参数 :采用 LinkedMultiValueMap ,不能使用HashMap

String url = 'http://posturl';
  MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();        
 map.add("shopid","1");       
 HttpHeaders headers = new HttpHeaders();       
 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);        
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);        
return restTemplate.postForEntity(url, request,String.class);
  • 注意 上面的请求支持参数类型均为String类型,如果MultiValueMap<String, Object> LinkedMultiValueMap 会将value放进list中,key --> [value]

2 采用JSONObject或者实体类传递参数

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        
        JSONObject param = new JSONObject();
        param.put("username", "123");
        
        HttpEntity<String> formEntity = new HttpEntity<String>(param, headers);
 
        String result = restTemplate.postForObject(url, formEntity, String.class);
  • 使用这种方式可以传递任意类型的参数,避免上面的情况

总结,遇到这种问题时多看看源码会很有帮助。

public class LinkedMultiValueMap<K, V> implements MultiValueMap<K, V>, Serializable, Cloneable {
    private static final long serialVersionUID = 3801124242820219131L;
    private final Map<K, List<V>> targetMap;
 
    public LinkedMultiValueMap() {
        this.targetMap = new LinkedHashMap();
    }
 
    public LinkedMultiValueMap(int initialCapacity) {
        this.targetMap = new LinkedHashMap(initialCapacity);
    }
 
    public LinkedMultiValueMap(Map<K, List<V>> otherMap) {
        this.targetMap = new LinkedHashMap(otherMap);
    }
 
    @Nullable
    public V getFirst(K key) {
        List<V> values = (List)this.targetMap.get(key);
        return values != null && !values.isEmpty() ? values.get(0) : null;
    }
 
    public void add(K key, @Nullable V value) {
        List<V> values = (List)this.targetMap.computeIfAbsent(key, (k) -> {
            return new LinkedList();
        });
        values.add(value);
    }
    public void addAll(K key, List<? extends V> values) {
        List<V> currentValues = (List)this.targetMap.computeIfAbsent(key, (k) -> {
            return new LinkedList();
        });
        currentValues.addAll(values);
    }
    public void addAll(MultiValueMap<K, V> values) {
        Iterator var2 = values.entrySet().iterator();
        while(var2.hasNext()) {
            Entry<K, List<V>> entry = (Entry)var2.next();
            this.addAll(entry.getKey(), (List)entry.getValue());
        }
    }
    public void set(K key, @Nullable V value) {
        List<V> values = new LinkedList();
        values.add(value);
        this.targetMap.put(key, values);
    }
    public void setAll(Map<K, V> values) {
        values.forEach(this::set);
    }
    public Map<K, V> toSingleValueMap() {
        LinkedHashMap<K, V> singleValueMap = new LinkedHashMap(this.targetMap.size());
        this.targetMap.forEach((key, values) -> {
            if (values != null && !values.isEmpty()) {
                singleValueMap.put(key, values.get(0));
            }
 
        });
        return singleValueMap;
    }
上一篇:精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用


下一篇:简单记录下RestTemplate中exchange()方法的使用