resttemplate使用post 方式 同时提交formData 和body 数据

网上很多方式使用resttemplate提交的时候 在构造HttpEntity对象时 ,要么使用如下方法

1 String jsonData = JSON.toJSONString(vo);
2         HttpHeaders headers = new HttpHeaders();
3         headers.setContentType(MediaType.APPLICATION_JSON);
4         HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);

此方法  json 出现在body 体里面

还有一种方法  提交formdata的方式,构造一个map  如下:

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("method", UPLOAD_METHOD);
        map.add("timestamp", timestamp + "");
        map.add("sign", SIGN);
        map.add("companyNo", companyNo);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> request = new HttpEntity<>(map , headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);

其实 post  提交分三种东东在里面 

header 

query  

body

而springboot 中 fromdata 是可以作为query 部分来提交的(其他框架不确定)

如下

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("method", UPLOAD_METHOD);
        map.add("timestamp", timestamp + "");
        map.add("sign", SIGN);
        map.add("companyNo", companyNo);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiURL).queryParams(map);
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(builder.toUriString(), request, JSONObject.class);

使用UriComponentsBuilder  将map构造在url里面

原文地址:https://www.cnblogs.com/niceletter/p/11822390.html