我尝试将数据从 Android 客户端作为 POST 请求发送到我的 Web API 后端,但它返回 404 响应代码。这是我的代码:
Backend:
[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment(string comment, string email, string actid)
{
string status = CC.PostNewComment(comment, email, actid);
return Ok(status);
}
安卓代码:
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对我的 Android 客户端的响应代码。我的代码不正确吗?错误之处还请指出:)
我通过正确设置后端来接受 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 代码正确传递参数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)