简体   繁体   English

如何使用Spring的RestTemplate等效于curl命令?

[英]How I do the equivalent of this curl command using Spring's RestTemplate?

I am successful posting a file to the same web service using the following: 我使用以下命令成功将文件发布到相同的Web服务:

curl -X POST http://<someUrl> -F "file=@/path/to/aFile.txt"

Now I am attempting to perform the same type of operation using Spring's RestTemplate with the caveat that I want to send a Java Object. 现在,我尝试使用Spring的RestTemplate执行与我要发送Java对象的警告相同的操作类型。 Here is an example of what I tried: 这是我尝试过的一个示例:

File file = File.createTempFile("aaa","bbb");
FileUtils.writeStringToFile(file, mapper.writeValueAsString(message), "UTF-8");

MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
values.add("file", new FileSystemResource(file));

restTemplate.postForObject(URL, values, String.class);

Where mapper is an instance of Jackson's ObjectMapper (v1.9.6) and FileUtils is from Apache's Common. 其中mapper是Jackson的ObjectMapper(v1.9.6)的实例,而FileUtils则来自Apache的Common。

The REST service requires the content type to be multipart/form-data so what I attempted to do was write the Java Object as a JSON string to a temporary file and then post the temporary file. REST服务要求内容类型为multipart / form-data,因此我试图做的是将Java Object作为JSON字符串写入临时文件,然后发布该临时文件。 Unfortunately I am getting an HTTP 500 Internal Server Error. 不幸的是,我收到HTTP 500内部服务器错误。

What am I doing wrong? 我究竟做错了什么? Any suggestions as to how to do this? 有关如何执行此操作的任何建议?

Looks like I solved it. 看来我解决了。 Here is what I did for reference: 这是我做的参考:

File file = File.createTempFile("aaa","bbb");
FileUtils.writeStringToFile(file, mapper.writeValueAsString(message), "UTF-8");

MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
values.add("name", file.getAbsolutePath());
values.add("filename", file.getAbsolutePath());
values.add("file", new FileSystemResource(file));

restTemplate.postForObject(URL, values, String.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM