使用RestTemplate发送multipart/form-data格式的数据

现有业务场景需要使用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;
}

 PS:对于上面的代码进行操作之后发现如果相应的参数中包含中文就会出现乱码,所以做了一下修改:

public Object sendRequest(Object obj) {
        RestTemplate restTemplate = new RestTemplate();

        //对中文格式数据进行处理
        FormHttpMessageConverter fc = new FormHttpMessageConverter();
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(stringConverter);
        partConverters.add(new ResourceHttpMessageConverter());
        fc.setPartConverters(partConverters);
        restTemplate.getMessageConverters().addAll(Arrays.asList(fc,new MappingJackson2HttpMessageConverter()));
        
        
         //发送请求,设置请求返回数据格式为String(去除上面方法中使用的httpEntity)
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http:xxx.xx", popHeaders(obj), 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;
}
posted @ 2017-11-01 10:50  Johnson_wang  阅读(40650)  评论(2编辑  收藏  举报