简体   繁体   中英

Coding Android/Java connection to ASP.Net Web API

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.

In your Java code you are using HttpPost in your APS.NET/MVC website you have posted GetCourse which is a "Get" Action. For MVC Controller actions, you have to add [HttpPost] (or rather [HttpPost, ActionName("Create")] to avoid Naming conflicts with the same named get Action) Attribute

But this doesn't really comply with RESTful design. For obtaining data you should always use GET method. Use "POST" only when resources are being updated or created (ie deleting, updating, inserting) and "PUT" to replace them. If you work with JavaScript (ie from website) then use POST instead of PUT, since JavaScript can only handle POST and GET.

So simply use HttpGet in your JavaCode and remove the NameValuePair stuff as it's not required in GET. Other than that the coude seems fine, but only using it for operation that change the resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM