POST数据从Android的对Web API返回404 [英] POST data from Android to Web API returns 404

查看:368
本文介绍了POST数据从Android的对Web API返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的Andr​​oid客户端作为一个POST请求我的Web API后端发送数据,但它返回一个404响应code。这是我的code:

I'm trying to send data from my Android client as a POST request to my Web API Backend but it returns a 404 response code. Here's my code:

后端

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

的Andr​​oid code:

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) {
}

然而,这会返回一个 404 响应code我的Andr​​oid客户端。难道我的code不正确的?请指出错误:)

However this returns a 404 Response code to my Android Client. Is my Code incorrect? Please point out the mistakes :)

推荐答案

我通过正确设置我的后台接受了Android客户端发送的参数解决了这个问题。问题是我的后台,不是我的客户端。

I fixed this by properly setting up my backend to accept the parameters sent by the android client. The problem was with my backend, not my client.

下面是我的后台:

[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]强制方法来读取请求的身体,我用一个模型来获取客户端传递的值。该方法会自动从请求获取值,并将其设置为模型使它很容易。

I used the [FromBody] to force the method to read the request body and I used a model to get the values passed by the client. The method automatically gets the values from the request and sets them to the model making it very easy.

请确保您的Andr​​oid客户端正确传递的参数有正确的POST code。

这篇关于POST数据从Android的对Web API返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆