繁体   English   中英

无法使用Spring RestTemplate将混合了MultiPartFile的POST参数发送到Rest Service

[英]Unable to send POST parameters with mix of MultiPartFile to Rest Service using spring RestTemplate

我有如下定义的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();

我无法从控制器(服务器)读取请求参数:收到以下错误

错误:请求中没有请求参数projectName

因此,请向我建议实现此目标的方法。

根据HttpEntity javadoc ,第一个参数是请求正文,第二个参数是请求标头,但是您的客户HttpEntity在请求正文中发送请求参数,并且您的控制器将其期望为@RequestParam ,因此出错。

因此,要么更改您的客户端以在端点地址URL中发送请求参数,以将您的服务器端匹配为...projectName=FirstProject&appId= app12345&version=1.0....

或将所有@RequestParam字段封装在一个DTO类中,如果客户端要发送请求正文,则在服务器端添加@RequestBody批注。

暂无
暂无

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

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