我的 Spring Rest 服务定义如下。
@RequestMapping(value = "/mobilebuild", method = RequestMethod.POST)
public StringWrapper buildApp(@RequestParam("projectName") String projectName, @RequestParam("appId") String projectId, @RequestParam("version") String version, @RequestParam("app") MultipartFile file) {
//Process to build app
return WMUtils.SUCCESS_RESPONSE;
}
从客户端我使用休息模板如下
final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter(Charset.forName(CommonConstants.UTF8)));
messageConverters.add(new ResourceHttpMessageConverter());
messageConverters.add(new SourceHttpMessageConverter<Source>());
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
RestTemplate template = new RestTemplate(messageConverters);
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
//Post Parameters
parts.add("projectName", "FirstProject");
parts.add("appId", "app12345");
parts.add("version", "1.0");
// MultipartFile
parts.add("app", new FileSystemResource(tempFilesStorageManager.getFilePath("/tmp/app.zip")));
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", auth);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String url = "http://localhost:8080/AppManager/services/mobilebuild";
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(parts, headers);
ResponseEntity<String> responseEntity = template.postForEntity(endpointAddress, requestEntity, String.class);
String response = responseEntity.getBody();
我无法从 Controller (服务器)读取请求参数:出现以下错误
错误:请求参数 projectName
不存在于请求中。
所以请建议我实现这一目标的方法。
最佳答案
根据javadoc HttpEntity
的第一个参数是请求正文,第二个参数是请求 header ,但是您的客户端在请求正文中发送请求参数,而您的 Controller 期望它们为 @RequestParam
,因此出现错误。
因此,要么更改您的客户端,以在端点地址 URL 中发送请求参数,以匹配您的服务器端 ...projectName=FirstProject&appId= app12345&version=1.0....
或者,如果您的客户端想要在请求正文中发送,则将所有 @RequestParam
字段封装在单个 DTO 类中,并在服务器端添加 @RequestBody
注释。
关于java - 无法使用 Spring RestTemplate 将 MultiPartFile 混合的 POST 参数发送到 Rest 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816913/