POST data from Android to Web API returns 404

2020-02-29 23:22发布

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:

Backend:

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

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

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

1条回答
倾城 Initia
2楼-- · 2020-03-01 00:18

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.

Here's my backend:

[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; }
}

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.

MAKE SURE that your android client is properly passing your parameters with a correct POST code.

查看更多
登录 后发表回答