现有业务场景需要使用RestTemplate发送一个post请求,请求格式为multipart/form-data的,可以使用一下方法
public Object sendRequest(Object obj) { RestTemplate restTemplate = new RestTemplate(); //设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>( popHeaders(obj), headers); //发送请求,设置请求返回数据格式为String ResponseEntity<String> responseEntity = restTemplate.postForEntity("http:xxx.xx", request, String.class); } //组装请求体 protected MultiValueMap<String, String> popHeaders(Object obj) { SubmitOrderDTO submit = (SubmitOrderDTO) obj; MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("order_id", submit.getOrderId()); map.add("userName",submit.getUserName()); //..... return map; }
时间: 2024-10-11 03:37:46