当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑
1POST传递参数 :采用 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; }