1

Ok I am struggling to build this HttpPost thing correctly... I built an ASP.Net web api with mvc 4, and am currently trying to pull data from one of the controllers in my android app. This is my code in android (java) but I do not know how to write it correctly to interface with ASP.Net (like the headers, the namevaluepairs, etc). I will post the controller code as well.

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(http://proopt.co.za.winhost.wa.co.za/api/Course);
    List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
    nameValue.add(new BasicNameValuePair("", ""));
    httppost.setEntity(new UrlEncodedFormEntity(nameValue));
    httppost.setHeader("Content-type", "application/json");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

And my controller as follows:

// GET api/Course/5
public Course GetCourse(string id)
{
    Course course = db.Courses.Find(id);
    if (course == null)
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
    }

    return course;
}

The URL I use for the http post is http://proopt.co.za.winhost.wa.co.za/api/Course

Please assist me, thanks.

UPDATE 2017

Use a RESTful API to interface with remote databases. Your client app should make use of some token-based authentication, and Retrofit 2.0 is a fantastic library for consuming remote REST APIs.

4

1 回答 1

2

HttpPost在您发布的 APS.NET/MVC 网站中使用的 Java 代码中,GetCourse这是一个“获取”操作。对于 MVC 控制器操作,您必须添加[HttpPost](或者更确切地说[HttpPost, ActionName("Create")]是避免与同名 get 操作发生命名冲突)属性

但这并不真正符合RESTful设计。要获取数据,您应该始终使用 GET 方法。仅在更新或创建资源(即删除、更新、插入)时使用“POST”,然后使用“PUT”替换它们。如果您使用 JavaScript(即来自网站),则使用 POST 而不是 PUT,因为 JavaScript 只能处理 POST 和 GET。

因此,只需HttpGet在您的 JavaCode 中使用并删除这些NameValuePair东西,因为它在 GET 中不需要。除此之外,coude 看起来不错,但仅将其用于更改资源的操作。

于 2013-08-23T03:04:11.303 回答