从Android到Web API的POST数据返回404

时间:2015-07-17 14:26:29

标签: android asp.net rest asp.net-web-api azure-mobile-services

我尝试将数据从我的Android客户端作为POST请求发送到我的Web API后端,但它返回404响应代码。这是我的代码:

后端

[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment(string comment, string email, string actid)
{
       string status = CC.PostNewComment(comment, email, actid);
       return Ok(status);
}

Android代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MYWEBADDRESS.azure-mobile.net/api/postcomment");
String mobileServiceAppId = "AZURE_SERVICE_APP_ID";

try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("comment", comment));
        nameValuePairs.add(new BasicNameValuePair("email", currEmail));
        nameValuePairs.add(new BasicNameValuePair("actid", currActID));

        httppost.setHeader("Content-Type", "application/json");
        httppost.setHeader("ACCEPT", "application/json");
        httppost.setHeader("X-ZUMO-APPLICATION", mobileServiceAppId);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
        httppost.setEntity(formEntity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

} 
catch (Exception e) {
}

然而,这会向我的Android客户端返回 404 响应代码。我的代码不正确吗?请指出错误:)

1 个答案:

答案 0 :(得分:5)

我通过正确设置后端来接受android客户端发送的参数来解决这个问题。问题在于我的后端,而不是我的客户。

这是我的后端:

[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody] CommentViewModel model)
{
       string comment = model.Comment;
       //Do your processing
       return Ok(return_something);
}

public class CommentViewModel
{
        public string Comment { get; set; }
        public string Email { get; set; }
        public string Actid { get; set; }
}

我使用[FromBody]强制方法读取请求体,我使用模型来获取客户端传递的值。该方法自动从请求中获取值并将它们设置为模型,使其变得非常容易。

请确保您的Android客户端使用正确的POST代码正确传递参数。