开发者

Receiving POST Request on Server (Spring Framework) from Android Application

I am sending a POST reques开发者_JAVA技巧t to a Server from my Android Application. The Server is developed using Spring Framework. The request is received by the server but the parameter that I was sending is null/empty (shown in the log).

The code used to send POST request is:

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

I have also tried to set HttpParams as follows but it has also failed:

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

The code on Server side that received this request is:

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

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

    return null;
}

The Logger message that I am logging shows:

Received POST request:

Any ideas what I am missing here ?


Perhaps Spring isn't converting your POST body into a Model. If that is the case, it will not know what the attribute json is on your Model because there is no Model!

Take a look at the Spring Documentation regarding mapping the request body.

You should be able to use Springs MessageConverter implementations to do what you want. Specifically, take a look at the FormHttpMessageConverter, which converts form data to/from a 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;
}

Adding this line to your xml configuration should enable the FormHttpMessageConverter by default:

<mvc:annotation-driven/>


I have used the RequestParam Annotation and it works for me. Now the code on server is as follows:

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

    return null;
}


I think you need add a content-type header from the client. The MessageConverter for JSON registers it self with a couple of content-type it will accept, one is application/json.

If you send with a content-type not handled by any MessageConvert it won't work.

Try adding "Content-type: application/json" as a header.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜