網上很多方式使用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里面
