Java – how to set the content type of a file for multipart upload in using resttemplate (from the rest client)

The file I want to upload will always be an XML file I want to set content type to 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'

The original request is as follows:

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 ..

The content type of the file is being generated as "application / octet stream", where I want it to be "application / XML". How do I set the content type of the file?

Solution

After extracting from this link, I found a solution:

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

The solution is to put the bytearrayresource in the httpentity with the required header and add the httpentity to the multivaluemap (instead of adding the bytearrayresource itself)

Code:

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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>