Consume ASP.NET WebApi HTTP service in Android with HTTP POST
我已经实现了ASP.NET WebApi,并通过HTTPPOST在Android应用程序中使用了它。 较少参数的方法可以完美地调用,但是带有参数的方法在与Google Chrome中的Advanced Rest Client一起使用时也无法正常工作,并且与HTTP GET一起使用也可以完美地工作。
Android中的呼叫者代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | String url ="http://192.168.15.3/api/user" HttpPost postMethod = new HttpPost(url); postMethod.setHeader("Content-Type","application/json; charset=utf-8"); postMethod.setHeader("Accept","*/*"); postMethod.setHeader("Accept-Encoding","gzip, deflate"); postMethod.setHeader("Accept-Language","en-US,en;q=0.8"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("id","1")); DefaultHttpClient hc = new DefaultHttpClient(); HttpResponse response; postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); response = hc.execute(postMethod); HttpEntity entity = response.getEntity(); InputStream inStream = entity.getContent(); String result = convertStreamToString(inStream); Log.e("Result:", result); |
控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class UserController : ApiController { UserCredentials[] users = new UserCredentials[] { new UserCredentials { User_ID ="1", User_Name ="testuser", Password ="test", First_Name ="Test", Last_Name ="User", Email ="[email protected]", Phone ="123456789", Mobile ="123456789", User_Type ="user" }, new UserCredentials { User_ID ="2", User_Name ="testuser2", Password ="test", First_Name ="Test", Last_Name ="User", Email ="[email protected]", Phone ="123456789", Mobile ="123456789", User_Type ="user" } }; [AcceptVerbs("POST")] public IEnumerable<UserCredentials> GetAllUsers() { return users; } [AcceptVerbs("POST")] public IHttpActionResult GetUser(string id) { var user = users.FirstOrDefault((p) => p.User_ID.Equals(id)); if (user == null) { return NotFound(); } return Ok(user); } } |
错误:
{" Message":"未找到与请求URI'http://192.168.15.3/api/user'匹配的HTTP资源。"," MessageDetail":"在与用户URI匹配的控制器'User'上未找到任何操作 请求。"}
因为您的控制器没有任何匹配的httppost方法,所以抛出错误。 您正在尝试将数据发布到接受GET请求的方法。
WebApi使用基于约定的方法名称。 您的方法以" Get"开头,因此它将以以下方式映射请求:
获取所有用户-GET-/ api / users
通过ID获取用户-GET-/ api / users / id
因此,您可以使用HttpGet请求而不是POST来调用它们。