Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am sending a POST request 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 ?

like image 616
rizzz86 Avatar asked Oct 10 '11 14:10

rizzz86


1 Answers

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/>
like image 97
nicholas.hauschild Avatar answered Sep 28 '22 10:09

nicholas.hauschild