2015-09-28 100 views
1

我有如下定義的Spring Rest服務。無法使用Spring RestTemplate將MultiPartFile與混合的MultiPartFile發送到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

所以請建議我以這種方式實現。

回答

0

根據javadocHttpEntity,第一個參數是請求正文,第二個是請求頭,但是您的客戶端正在請求正文內發送請求參數,您的控制器期望它們爲@RequestParam,因此是錯誤。

因此,要麼改變你的客戶端發送請求參數在終點地址URL到你的服務器端匹配的...projectName=FirstProject&appId= app12345&version=1.0....

或封裝單個DTO類中所有的@RequestParam領域,在服務器端,如果添加@RequestBody註解你的客戶想要發送請求正文。

相關問題