The Best Android Networking Library for Fast and Easy Networking

About Fast Android Networking Library (supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH)
I recently published a library, which I believe to be the simplest way to handle networking with Android.
Here are some advantages of using my Fast Android Networking library over other libraries:
- OkHttpClient can be customized for every request easily — like timeout customization, etc. for each request.
- As it uses OkHttpClient and Okio, it is faster.
- Supports RxJava and RxJava2 — check here.
- Supports JSON Parsing to Java Objects (also support Jackson Parser).
- Complete analytics of any request can be obtained. You can know bytes sent, bytes received, and the time taken on any request. These analytics are important so that you can find the data usage of your application and the time taken for each request, so you can identify slow requests.
- You can get the current bandwidth and connection quality to write better logical code — download high quality images on excellent connection quality and low on poor connection quality.
- Proper Response Caching — which leads to reduced bandwidth usage.
- An executor can be passed to any request to get a response in another thread. If you are doing a heavy task with the response, you can not do that in main thread.
- A single library for all types of networking — download, upload, multipart.
- Prefetching of any request can be done so that it gives instant data when required from cache.
- All types of customization are possible.
- Immediate Request really is immediate now.
- Proper request cancelling.
- Prevents cancellation of a request if it’s completed more than specific threshold percentage.
- A simple interface to make any type of request.
Why should you use Fast Android Networking Library?
- Recent removal of HttpClient in Android Marshmallow(Android M) made other networking library obsolete.
- No other single library do each and everything like making request, downloading any type of file, uploading file, loading image from network in ImageView, etc. There are libraries but they are outdated.
- As it uses OkHttp, most important it supports HTTP/2.
- No other library provides simple interface for doing all types of things in networking like setting priority, cancelling, etc.
How to use the Fast Android Networking library:
## Using Fast Android Networking in your application
Add this in your build.gradle
compile 'com.amitshekhar.android:android-networking:1.0.2'
When using it with RxJava2
compile 'com.amitshekhar.android:rx2-android-networking:1.0.2'
When using it with RxJava
compile 'com.amitshekhar.android:rx-android-networking:1.0.2'
When using it with Jackson Parser
compile 'com.amitshekhar.android:jackson-android-networking:1.0.2'
Do not forget to add internet permission in manifest if already not present
<uses-permission android:name="android.permission.INTERNET" />
Then initialize it in onCreate() Method of application class, :
AndroidNetworking.initialize(getApplicationContext());
### Making a GET Request
AndroidNetworking.get("http://api.localhost.com/{pageNumber}/test")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.addHeaders("token", "1234")
.setTag("test")
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Making a POST Request
AndroidNetworking.post("http://api.localhost.com/createAnUser")
.addBodyParameter("firstname", "Amit")
.addBodyParameter("lastname", "Shekhar")
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
// You can also post java object
User user = new User();
user.firstname = "Amit";
user.lastname = "Shekhar";
AndroidNetworking.post("http://api.localhost.com/createAnUser")
.addBodyParameter(user) // posting java object
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Using it with your own JAVA Object - JSON Parser
/*--------------Example One -> Getting the userList----------------*/
AndroidNetworking.get("http://api.localhost.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {
@Override
public void onResponse(List<User> users) {
// do anything with response
Log.d(TAG, "userList size : " + users.size());
for (User user : users) {
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
}
@Override
public void onError(ANError anError) {
// handle error
}
});
/*--------------Example Two -> Getting an user----------------*/
AndroidNetworking.get("http://api.localhost.com/getAnUser/{userId}")
.addPathParameter("userId", "1")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.getAsObject(User.class, new ParsedRequestListener<User>() {
@Override
public void onResponse(User user) {
// do anything with response
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
@Override
public void onError(ANError anError) {
// handle error
}
});
/*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/
### Downloading a file from server
AndroidNetworking.download(url,dirPath,fileName)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.build()
.setDownloadProgressListener(new DownloadProgressListener() {
@Override
public void onProgress(long bytesDownloaded, long totalBytes) {
// do anything with progress
}
})
.startDownload(new DownloadListener() {
@Override
public void onDownloadComplete() {
// do anything after completion
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Uploading a file to server
AndroidNetworking.upload(url)
.addMultipartFile("image",file)
.setTag("uploadTest")
.setPriority(Priority.IMMEDIATE)
.build()
.setUploadProgressListener(new UploadProgressListener() {
@Override
public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
}
})
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Getting Response and completion in an another thread executor
(Note : Error and Progress will always be returned in main thread of application)
AndroidNetworking.upload(url)
.addMultipartFile("image",file)
.setTag("uploadTest")
.setPriority(Priority.IMMEDIATE)
.build()
.setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread
.setUploadProgressListener(new UploadProgressListener() {
@Override
public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
}
})
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// below code will be executed in the executor provided
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Cancelling a request.
Any request with a given tag can be cancelled. Just do like this.
AndroidNetworking.cancel("tag");
### Loading image from network into ImageView
<com.androidnetworking.widget.ANImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" />
imageView.setDefaultImageResId(R.drawable.default);
imageView.setErrorImageResId(R.drawable.error);
imageView.setImageUrl(imageUrl);
### Getting Bitmap from url with some specified parameters
AndroidNetworking.get(imageUrl)
.setTag("imageRequestTag")
.setPriority(Priority.MEDIUM)
.setBitmapMaxHeight(100)
.setBitmapMaxWidth(100)
.setBitmapConfig(Bitmap.Config.ARGB_8888)
.build()
.getAsBitmap(new BitmapRequestListener() {
@Override
public void onResponse(Bitmap bitmap) {
// do anything with bitmap
}
@Override
public void onError(ANError error) {
// handle error
}
});
### Prefetch a request (so that it can return from cache when required at instant)
AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY)
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "30")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.prefetch();
### Customizing OkHttpClient for a particular request
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor(new GzipRequestInterceptor())
.build();
AndroidNetworking.get("http://api.localhost.com/{pageNumber}/test")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.addHeaders("token", "1234")
.setTag("test")
.setPriority(Priority.LOW)
.setOkHttpClient(okHttpClient) // passing a custom okHttpClient
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
### ConnectionClass Listener to get current network quality and bandwidth
// Adding Listener
AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() {
@Override
public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) {
// do something on change in connectionQuality
}
});
// Removing Listener
AndroidNetworking.removeConnectionQualityChangeListener();
// Getting current ConnectionQuality
ConnectionQuality connectionQuality = AndroidNetworking.getCurrentConnectionQuality();
if(connectionQuality == ConnectionQuality.EXCELLENT){
// do something
}else if (connectionQuality == ConnectionQuality.POOR){
// do something
}else if (connectionQuality == ConnectionQuality.UNKNOWN){
// do something
}
// Getting current bandwidth
int currentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWN
### Getting Analytics of a request by setting AnalyticsListener on that
AndroidNetworking.download(url,dirPath,fileName)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.build()
.setAnalyticsListener(new AnalyticsListener() {
@Override
public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
Log.d(TAG, " bytesSent : " + bytesSent);
Log.d(TAG, " bytesReceived : " + bytesReceived);
Log.d(TAG, " isFromCache : " + isFromCache);
}
})
.setDownloadProgressListener(new DownloadProgressListener() {
@Override
public void onProgress(long bytesDownloaded, long totalBytes) {
// do anything with progress
}
})
.startDownload(new DownloadListener() {
@Override
public void onDownloadComplete() {
// do anything after completion
}
@Override
public void onError(ANError error) {
// handle error
}
});
Note : If bytesSent or bytesReceived is -1 , it means it is unknown
More examples and the Fast Android Networking Library Github Project are available here.
We need developers to contribute to this Fast Android Networking library and help make networking better on Android.
Using Fast Android Networking with RxJava can be read here.
For full details, visit the documentation on our web site:
Also, Let’s become friends on Twitter, Linkedin, Github, and Facebook.