zoukankan      html  css  js  c++  java
  • 使用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;
    }
  • 相关阅读:
    Win7 配置Android开发环境 狼人:
    Windows Phone 7 Tips (3) 狼人:
    Windows Phone 7 Tips (1) 狼人:
    探索移动Web网页编码设计 狼人:
    初探AIR for Android开发 狼人:
    Android设计趋势分析10则 狼人:
    Android与服务器端数据交互 狼人:
    Android UI基本测验:线性布局 狼人:
    Android用户界面设计:线性布局 狼人:
    Eclipse开发Android应用程序入门:重装上阵 狼人:
  • 原文地址:https://www.cnblogs.com/wangzun/p/7765387.html
Copyright © 2011-2022 走看看