简体   繁体   中英

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

I have Spring Rest service defined as below.

@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;
    }

From client side i am using rest template as follows

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();

I am unable to read the request parameters from controller (server): getting the following error

Error: request parameter projectName is not present in the request.

So please suggest me the way to achieve this.

According to javadoc of HttpEntity , the first parameter is request body and second one is request headers, but your client is sending request parameters inside request body and your controller is expecting them as @RequestParam , hence the error.

So either change your client to send the request parameters in the end point address URL to match your server side as ...projectName=FirstProject&appId= app12345&version=1.0....

Or encapsulate all your @RequestParam fields inside a single DTO class and add @RequestBody annotation on server side if your client wants to send in request body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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