2011-10-10 40 views
8

我正在從我的Android應用程序向服務器發送POST請求。服務器是使用Spring Framework開發的。該請求由服務器接收,但我發送的參數爲空/空(顯示在日誌中)。從Android應用程序接收服務器上的POST請求(Spring Framework)

用於發送POST請求的代碼是:

DefaultHttpClient hc=new DefaultHttpClient(); 
ResponseHandler <String> res=new BasicResponseHandler(); 

String postMessage = "json String"; 

HttpPost postMethod=new HttpPost("http://ip:port/event/eventlogs/logs"); 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
nameValuePairs.add(new BasicNameValuePair("json", postMessage)); 

postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
hc.execute(postMethod,res); 

我也曾嘗試設置的HttpParams如下,但它也失敗:

HttpParams params = new BasicHttpParams(); 
params.setParameter("json", postMessage); 
postMethod.setParams(params); 

接收到該服務器端的代碼請求是:

@RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST) 
public String logs(@ModelAttribute("json") String json) { 

    logger.debug("Received POST request:" + json); 

    return null; 
} 

我正在記錄的記錄器消息顯示:

Received POST request: 

任何想法我在這裏失蹤?

回答

4

我已經使用了RequestParam註釋,它爲我工作。現在服務器上的代碼如下:

@RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST) 
public String logs(@RequestParam("json") String json) { 
logger.debug("Received POST request:" + json); 

    return null; 
} 
+0

並在客戶端上指定參數作爲請求的實體。將它們指定爲setParams仍然不起作用。 –

+0

我有完全相同的問題。當我做你說的,我得到org.springframework.web.bind.MissingServletRequestParameterException:必需的整數參數'頻道'不存在。我使用基本名稱valuepair從android客戶端發送參數。你能幫我嗎? – Emilla

+0

@Emilla有可能您的參數可能會丟失,然後將其標記爲required = false。看到這個答案http://stackoverflow.com/a/3466851/867475 – rizzz86

7

也許春天沒有把你的POST身體變成Model。如果是這樣的話,它不會知道屬於您的Model,因爲沒有Model

看一看Spring Documentation regarding mapping the request body

你應該可以使用Springs MessageConverter實現你想做的事情。具體來說,請看FormHttpMessageConverter,它將表單數據轉換爲MultiValueMap<String, String>或從MultiValueMap<String, String>轉換。

@RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST) 
public String logs(@RequestBody Map<String,String> body) { 
    logger.debug("Received POST request:" + body.get("json")); 

    return null; 
} 

添加此行到您的xml配置應使FormHttpMessageConverter默認:

<mvc:annotation-driven/> 
+0

感謝@ nicholas.hauschild的迴應。我嘗試了RequestBody註釋,但它返回HTTP錯誤415不支持的媒體類型(http://www.checkupdown.com/status/E415.html)。之後,我通過RequestParam註釋替換了RequestBody註解,並且它可以工作。現在我正在獲取服務器上的POST請求參數。 – rizzz86

2

我認爲你需要從客戶端添加一個內容類型頭。 JSON的MessageConverter使用它可以接受的幾個內容類型註冊它自己,一個是application/json。

如果發送的內容類型沒有被任何MessageConvert處理,它將不起作用。

嘗試添加「Content-type:application/json」作爲標題。

+0

添加Content-Type標頭爲我工作,謝謝。 –

相關問題