您好我有2个独立的应用程序。
第一个是发送帖子请求: 我正在尝试将文件发送到第二个应用程序
public static String httpPostMultipartFile(String url, File file) throws IOException{
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("file", file); // load file into parameter
HttpHeaders headers1 = new HttpHeaders();
headers1.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = restTemplate.exchange(
url,
HttpMethod.POST,
new HttpEntity<MultiValueMap<String, Object>>(parameters, headers1),
String.class
).getBody();
return result;
这是获得发布请求的第二个应用
@RequestMapping(value = "/fileupload/save", method = RequestMethod.POST, produces = "text/plain")
@ResponseBody
public String save(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(required = false) Boolean suggestTranspose, @RequestParam(value = "transformers", required = false) String transformersString, @RequestParam(required = false) Integer brandId) throws Exception {
.....
}
但在我的第二个应用程序中,MultipartFile在其余调用中实际上是空的
我找到了这个链接,它帮助了我 link 1
答案 0 :(得分:2)
您的httpPostMultipartFile方法应如下所示。您需要使用new FileSystemResource(file.getPath())
添加文件。
public static String httpPostMultipartFile(String url, File file) throws IOException{
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();
multipartMap.add("file", new FileSystemResource(file.getPath()));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);
String result = restTemplate.exchange(
url,
HttpMethod.POST,
request,
String.class
).getBody();
return result;
}
答案 1 :(得分:0)
这是一个示例(由我测试)如何使用RestTemplate调用包含@RequestParam文件的Web服务:
import java.io.File;
import java.io.IOException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
public class Application {
public static void main(String[] args) throws IOException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
FileSystemResource value = new FileSystemResource(new File("src/myFile.txt"));
map.add("file", value);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange("http://localhost/api/ws/myws", HttpMethod.POST, requestEntity, String.class);
}
}