gpt4 book ai didi

java - 使用 RestTemplate 时如何在分段上传中设置文件的内容类型(来自休息客户端)

转载 作者:IT老高 更新时间:2023-10-28 13:51:20 29 4
gpt4 key购买 nike

我尝试上传的文件将始终是 xml 文件。我想将内容类型设置为 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/octet-stream”,而我希望它是“application/xml”如何设置文件的内容类型?

最佳答案

从这个链接中得到提示后,我想出了解决方案:

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

解决方案是将 ByteArrayResource 放入具有所需 header 的 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);

关于java - 使用 RestTemplate 时如何在分段上传中设置文件的内容类型(来自休息客户端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28373130/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com