2011-08-09 39 views
0

我正在嘗試測試我創建的休息服務。該服務是一個帖子。試圖用多部分文件測試休息服務

  1. 我想創建一個文件來傳遞參數(包括一個多部分文件)。
  2. 從那裏我試圖調用服務在這一點上。

很確定服務不起作用。但是當我打電話給休息服務。我有一個簡單的表單,它只傳遞包括jpg在內的幾個值。

這是代碼。

HttpMessageConverter bufferedIamageHttpMessageConverter = new ByteArrayHttpMessageConverter(); 
restTemplate.postForObject("http://localhost:8080/sendScreeenAsPostCard", uploadItem.getFileData(), String.class)); 

我的方法簽名是:

ResultStatus sendScreenAsPostcard(@RequestParam MultipartFile image, @RequestParamString userId) 

這就是我得到的錯誤。

Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]

回答

6

您需要模擬一個文件上傳,這需要一個特定的內容類型頭,機身參數等等這樣的事情應該做的伎倆:

// Fill out the "form"... 
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); 
parameters.add("file", new FileSystemResource("file.jpg")); // load file into parameter 
parameters.add("blah", blah); // some other form field 

// Set the headers... 
HttpHeaders headers = new HttpHeaders(); 
headers.set("Content-Type", "multipart/form-data"); // we are sending a form 
headers.set("Accept", "text/plain"); // looks like you want a string back 

// Fire! 
String result = restTemplate.exchange(
    "http://localhost:8080/sendScreeenAsPostCard", 
    HttpMethod.POST, 
    new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), 
    String.class 
).getBody(); 
+0

好,我想我可能會因爲你而取得一些進展。我收到一個404錯誤,我認爲這可能與我的post方法的簽名有關? –

+0

它看起來像使用Spring MVC的註釋,所以我希望你的'sendScreenAsPostcard'方法應該有'@RequestMapping(method = POST,value =「/ sendScreeenAsPostCard」)''。然後,根據web.xml,容器行爲等,在您的端點之前可能會有某些內容(例如,默認情況下,Tomcat希望WAR名稱在主機/端口之後)。在你的方法中還有3個e - 404由於錯字?最後,當Spring加載和東西配置正確時,您應該看到它記錄了它認爲它正在公開的所有端點,以便您可以驗證。 – SingleShot

+0

Allthree的觀點特別有用。現在我得到了一個406錯誤。我的拼寫錯了,我在電話中改變了我的參數,所以認爲這是問題所在。這是簽名。我得到了一個406錯誤和我收到的當前錯誤是500. @RequestMapping(value =「/ sendScreenAsPostcard」,method = {RequestMethod.POST}) –