从Android应用程序向服务器(Spring框架)发送POST请求

8
我将从我的安卓应用向服务器发送一个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;
}

我正在记录的日志消息显示:

Received POST request:

有什么想法我错过了什么吗?
3个回答

7
也许Spring没有将您的POST请求主体转换为Model。如果是这种情况,它将不知道您的Model上的属性json是什么,因为没有Model!请查看Spring文档有关映射请求正文的内容
您应该能够使用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/>

感谢@nicholas.hauschild的回复。我尝试了使用RequestBody注释,但它返回HTTP错误415 “不支持的媒体类型”(http://www.checkupdown.com/status/E415.html)。之后我用RequestParam注释替换了RequestBody注释,并且它奏效了。现在我可以在服务器上获取POST请求参数了。 - rizzz86

4

我已经使用了RequestParam注释,并且它对我很有效。现在服务器上的代码如下:

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

    return null;
}

在客户端,您需要将请求的实体指定为参数。将它们指定为setParams仍然无法工作。 - Adrian Aslau
我完全有同样的问题。当我按照你说的做时,我得到了org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'channel' is not present。我正在使用基本的名称值对从Android客户端发送参数。你能帮忙吗? - Emilla
@Emilla请问你的参数是否有可能被省略,如果是,请将其标记为required = false。请参考此答案https://dev59.com/X0_Ta4cB1Zd3GeqPDLn6#3466851。 - rizzz86

2

我认为您需要从客户端添加Content-Type头信息。JSON的MessageConverter会注册一些它可以接受的Content-Type,其中之一是application/json。

如果您发送了一个没有被任何MessageConverter处理的Content-Type,它将不起作用。

尝试添加"Content-type:application/json"作为头信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接