From Developer Library:
An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing. You can also use it in Service or background thread, library will automatically recognize in which context is ran.Set dependency to app gradle.
dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}
Then inside your activity you can call this method. The method is self descriptive.
private void Response() {
// create an object of AsyncHttpClient
AsyncHttpClient client = new AsyncHttpClient();
// then call several method like get, post , setBasicAuth with various parameters
// as you required
client.post("GIVE YOUR URL HERE", new JsonHttpResponseHandler() {
@Override
public void onStart() {
// Initiated the request
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d("onSuccess", "" + response);
// customized your JSON HERE
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobj2 = jsonArray.getJSONObject(i);
Log.e("", jobj2.getString("name"));
}
} catch (JSONException e) {
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
// In case you have got an JSONArray as response
// wrote code here
Log.d("onSuccess", "" + response);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
});
}
You need to require these two manifest permission.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Adding GET/POST Parameters with RequestParams The RequestParams class is used to add optional GET or POST parameters to your requests. RequestParams can be built and constructed in various ways: Create empty RequestParams and immediately add some parameters:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
Create RequestParams for a single parameter:
RequestParams params = new RequestParams("single", "value");
Create RequestParams from an existing Map of key/value strings:
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
You can call get method as like as follows
client.get(URL, params, responseHandler object);