加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何在使用RestTemplate(从休息客户端)中为多部分上传中

发布时间:2020-12-14 05:06:17 所属栏目:Java 来源:网络整理
导读:我想要上传的文件将始终是一个xml文件.我想将content-type设置为application / xml 这是我的代码: MultiValueMapString,Object parts = new LinkedMultiValueMapString,Object(); parts.add("subject","some info"); ByteArrayResource xmlFile = new ByteA
我想要上传的文件将始终是一个xml文件.我想将content-type设置为application / xml
这是我的代码:
MultiValueMap<String,Object parts = new LinkedMultiValueMap<String,Object(); parts.add("subject","some info"); 
         ByteArrayResource xmlFile = new    ByteArrayResource(stringWithXMLcontent.getBytes("UTF-8")){
                 @Override
                 public String getFilename(){
                     return documentName;
                 }             
             };

     parts.add("attachment",xmlFile);

//sending the request using RestTemplate template;,the request is successfull 
String result = template.postForObject(getRestURI(),httpEntity,String.class);      
//but the content-type of file is 'application/octet-stream'

原始请求如下所示:

Content-Type:
    multipart/form-data;boundary=gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz
    User-Agent: Java/1.7.0_67 Host: some.host Connection: keep-alive
    Content-Length: 202866

    --gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz Content-Disposition: form-data;    name="subject" Content-Type: text/plain;charset=ISO-8859-1
    Content-Length: 19

    some info

    --gbTw7ZJbcdbHIeCRqdX81DVTFfA-oteHHEqgmlz Content-Disposition: form-data;   name="attachment"; filename="filename.xml" Content-Type:
    application/octet-stream Content-Length: 201402

    ....xml file contents here ..

该文件的内容类型正在生成为“应用程序/八位字节流”,其中我希望它是“application / xml”
我如何设置文件的内容类型?

解决方法

从此链接中提取出来后,我找出了解决方案:

Making a multipart post request with compressed jpeg byte array with spring for android

解决方案是将ByteArrayResource放在具有所需标头的HttpEntity中,并将HttpEntity添加到Multivaluemap(而不是添加ByteArrayResource本身).

码:

Resource xmlFile = new ByteArrayResource(stringWithXMLcontent.getBytes("UTF-8")){
            @Override
            public String getFilename(){
                return documentName;
            }
        };
        HttpHeaders xmlHeaders = new HttpHeaders();
        xmlHeaders.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Resource> xmlEntity = new HttpEntity<Resource>(xmlFile,xmlHeaders);
        parts.add("attachment",xmlEntity);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读