Android App Development and Web Server Interactions

后端 未结 4 1642
轻奢々
轻奢々 2021-01-01 07:45

I am just learning about Android Development so excuse me if this is a bit off in nature. I am wanting to make an app that interacts with a Database from my website, in a se

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 07:54

    I'm sure there are libraries out there for Android that help you with HTTP Get and Post, however, if you really want to understand what is going there are just a couple of classes you have to understand in order to make the necessary classes yourself.

    First, get to know HttpClient, HTTPGet, HTTPPost, and HTTPResponse. Some of the later versions of Android have some nice other classes as well, but those four is pretty much all you need to get started.

    You need to do something like this:

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://www.myurl.com/api_name");
    HttpResponse response = client.execute(request);
    

    If you debug this (with a real URL of course), you'll notice that your app kind of freezes during client.execute(). This is the point at which the request has actually fired and the app is waiting for a response. Once you actually get the response, it isn't very difficult to get the data out of it.

    Once you understand this, you'll want to get to know AsyncTask, which is endlessly useful for performing background tasks. You can find the documentation here: http://developer.android.com/reference/android/os/AsyncTask.html There is a great example of how to use this right at the top.

    Using these two concepts together you can perform asynchronous HTTP requests. Basically, put your actual HTTP execute code in doInBackground of your AsyncTask. At the end of the doInBackground return your response, and then do what you want with your data in the AsyncTask's onPostExecute.

提交回复
热议问题