gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:10:59 25 4
gpt4 key购买 nike

我正在尝试将数据作为 POST 请求从我的 Android 客户端发送到我的 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);
}

安卓代码:

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 响应代码。我的代码不正确吗?错误之处请指出:)

最佳答案

我通过正确设置我的后端来接受 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 代码正确传递您的参数。

关于android - 从 Android 到 Web API 的 POST 数据返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31478149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com