riz*_*z86 8 post spring android spring-mvc
我正从我的Android应用程序向服务器发送POST请求.服务器是使用Spring Framework开发的.请求由服务器接收,但我发送的参数为null/empty(显示在日志中).
用于发送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);
Run Code Online (Sandbox Code Playgroud)
我也尝试按如下方式设置HttpParams,但它也失败了:
HttpParams params = new BasicHttpParams();
params.setParameter("json", postMessage);
postMethod.setParams(params);
Run Code Online (Sandbox Code Playgroud)
服务器端收到此请求的代码是:
@RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST)
public String logs(@ModelAttribute("json") String json) {
logger.debug("Received POST request:" + json);
return null;
}
Run Code Online (Sandbox Code Playgroud)
我正在记录的Logger消息显示:
Received POST request:
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么想法?
也许春天不会把你的POST
身体变成一个Model
.如果是这种情况,它将不知道你的属性json
是什么,Model
因为没有Model
!
您应该能够使用Springs MessageConverter
实现来执行您想要的操作.具体来说,看一下FormHttpMessageConverter
将表单数据转换为/从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;
}
Run Code Online (Sandbox Code Playgroud)
将此行添加到xml配置应FormHttpMessageConverter
默认启用:
<mvc:annotation-driven/>
Run Code Online (Sandbox Code Playgroud)
我已经使用了 RequestParam 注释,它对我有用。现在服务器上的代码如下:
@RequestMapping(value = "/eventlogs/logs", method = RequestMethod.POST)
public String logs(@RequestParam("json") String json) {
logger.debug("Received POST request:" + json);
return null;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
23710 次 |
最近记录: |