Monday, November 23, 2015

Sending a Network Request in android

Now, we just create an AsyncHttpClient, and then execute a request specifying an anonymous class as a callback:
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;

AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.get("http://www.google.com", params, new TextHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, String res) {
            // called when response HTTP status is "200 OK"
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        } 
    }
);
This will automatically execute the request asynchronously and fire the onSuccess when the response returns a success code and onFailure if the response does not.

No comments:

Post a Comment