我正在从我的 Android 应用程序向服务器发送 POST 请求。服务器是使用 Spring 框架开发的。服务器收到请求,但我发送的参数为 null/空(显示在日志中)。
用于发送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;
}
我正在记录的 Logger 消息显示:
Received POST request:
知道我在这里遗漏了什么吗?
最佳答案
也许 Spring 没有转换你的 POST
body 变成了Model
.如果是这样的话,它就不知道json
是什么属性了。在你的 Model
上因为没有 Model
!
看看 Spring Documentation regarding mapping the request body .
您应该能够使用 Spring MessageConverter
实现来做你想做的事。具体看一下FormHttpMessageConverter
, 将表单数据与 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/>
关于android - 从 Android 应用程序接收服务器(Spring Framework)上的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7714124/