resttemplate使用post 方式 同時提交formData 和body 數據

網上不少方式使用resttemplate提交的時候 在構造HttpEntity對象時 ,要麼使用以下方法spring

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 體裏面json

 

還有一種方法  提交formdata的方式,構造一個map  以下:api

        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  提交分三種東東在裏面 springboot

header 框架

query  post

bodyui

而springboot 中 fromdata 是能夠做爲query 部分來提交的(其餘框架不肯定)url

以下spa

        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裏面rest

相關文章
相關標籤/搜索