Fast Android Networking Library is a powerful library for doing any type of networking in Android applications which is made on top of OkHttp Networking Layer.
Fast Android Networking Library takes care of each and everything. So you don't have to do anything, just make request and listen for the response.
- 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.
- No other library provided simple interface for doing all types of things in networking like setting priority, cancelling, etc.
- As it uses Okio , No more GC overhead in android application. Okio is made to handle GC overhead while allocating memory. Okio do some clever things to save CPU and memory.
- As it uses OkHttp , most important it supports HTTP/2.
RxJava2 Support, check here.
RxJava2 + Fast Android Networking + Dagger2 with MVP Architecture Project, Check here
- Support it by clicking the ⭐ button on the upper right of this page. ✌️
For full details, visit the documentation on our web site :
Fast Android Networking Library can be included in any Android application.
Fast Android Networking Library supports Android 2.3 (Gingerbread) and later.
Add this in your build.gradle
compile 'com.amitshekhar.android:android-networking:0.4.0'Do not forget to add internet permission in manifest if already not present
<uses-permissionandroid:name="android.permission.INTERNET" />Then initialize it in onCreate() Method of application class :
AndroidNetworking.initialize(getApplicationContext());Initializing it with some customization , as it uses OkHttp as networking layer, you can pass custom okHttpClient while initializing it.
// Adding an Network Interceptor for Debugging purpose :OkHttpClientokHttpClient = newOkHttpClient() .newBuilder()
.addNetworkInterceptor(newStethoInterceptor())
.build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient); Using the Fast Android Networking with Jackson Parser
compile 'com.amitshekhar.android:jackson-android-networking:0.4.0'// Then set the JacksonParserFactory like belowAndroidNetworking.setParserFactory(newJacksonParserFactory());AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.addHeaders("token", "1234")
.setTag("test")
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(newJSONArrayRequestListener() {
@OverridepublicvoidonResponse(JSONArrayresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
.addBodyParameter("firstname", "Amit")
.addBodyParameter("lastname", "Shekhar")
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(newJSONObjectRequestListener() {
@OverridepublicvoidonResponse(JSONObjectresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});You can also post java object, json, file, etc in POST request like this.
Useruser = newUser();
user.firstname = "Amit";
user.lastname = "Shekhar";
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
.addBodyParameter(user) // posting java object
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONArray(newJSONArrayRequestListener() {
@OverridepublicvoidonResponse(JSONArrayresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});
JSONObjectjsonObject = newJSONObject();
try {
jsonObject.put("firstname", "Amit");
jsonObject.put("lastname", "Shekhar");
} catch (JSONExceptione) {
e.printStackTrace();
}
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
.addJSONObjectBody(jsonObject) // posting json
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONArray(newJSONArrayRequestListener() {
@OverridepublicvoidonResponse(JSONArrayresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
.addFileBody(file) // posting any type of file
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(newJSONObjectRequestListener() {
@OverridepublicvoidonResponse(JSONObjectresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); /*--------------Example One -> Getting the userList----------------*/AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.getAsObjectList(User.class, newParsedRequestListener<List<User>>() {
@OverridepublicvoidonResponse(List<User> users) {
// do anything with responseLog.d(TAG, "userList size : " + users.size());
for (Useruser : users) {
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
}
@OverridepublicvoidonError(ANErroranError) {
// handle error
}
});
/*--------------Example Two -> Getting an user----------------*/AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
.addPathParameter("userId", "1")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.getAsObject(User.class, newParsedRequestListener<User>() {
@OverridepublicvoidonResponse(Useruser) {
// do anything with responseLog.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
@OverridepublicvoidonError(ANErroranError) {
// handle error
}
}); /*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/AndroidNetworking.download(url,dirPath,fileName)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.build()
.setDownloadProgressListener(newDownloadProgressListener() {
@OverridepublicvoidonProgress(longbytesDownloaded, longtotalBytes) {
// do anything with progress
}
})
.startDownload(newDownloadListener() {
@OverridepublicvoidonDownloadComplete() {
// do anything after completion
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); AndroidNetworking.upload(url)
.addMultipartFile("image",file) .addMultipartParameter("key","value")
.setTag("uploadTest")
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(newUploadProgressListener() {
@OverridepublicvoidonProgress(longbytesUploaded, longtotalBytes) {
// do anything with progress
}
})
.getAsJSONObject(newJSONObjectRequestListener() {
@OverridepublicvoidonResponse(JSONObjectresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); (Note : Error and Progress will always be returned in main thread of application)
AndroidNetworking.upload(url)
.addMultipartFile("image",file) .addMultipartParameter("key","value") .setTag("uploadTest")
.setPriority(Priority.HIGH)
.build()
.setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread
.setUploadProgressListener(newUploadProgressListener() {
@OverridepublicvoidonProgress(longbytesUploaded, longtotalBytes) {
// do anything with progress
}
})
.getAsJSONObject(newJSONObjectRequestListener() {
@OverridepublicvoidonResponse(JSONObjectresponse) {
// below code will be executed in the executor provided// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); Setting a Percentage Threshold For Not Cancelling the request if it has completed the given threshold
AndroidNetworking.download(url,dirPath,fileName)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50%
.build() // downloading is done.But can be cancalled with forceCancel.
.setDownloadProgressListener(newDownloadProgressListener() {
@OverridepublicvoidonProgress(longbytesDownloaded, longtotalBytes) {
// do anything with progress
}
})
.startDownload(newDownloadListener() {
@OverridepublicvoidonDownloadComplete() {
// do anything after completion
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); Any request with a given tag can be cancelled. Just do like this.
AndroidNetworking.cancel("tag"); // All the requests with the given tag will be cancelled.AndroidNetworking.forceCancel("tag"); // All the requests with the given tag will be cancelled , even if any percent threshold is// set , it will be cancelled forcefully. AndroidNetworking.cancelAll(); // All the requests will be cancelled. AndroidNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is// set , it will be cancelled forcefully. <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); AndroidNetworking.get(imageUrl)
.setTag("imageRequestTag")
.setPriority(Priority.MEDIUM)
.setBitmapMaxHeight(100)
.setBitmapMaxWidth(100)
.setBitmapConfig(Bitmap.Config.ARGB_8888)
.build()
.getAsBitmap(newBitmapRequestListener() {
@OverridepublicvoidonResponse(Bitmapbitmap) {
// do anything with bitmap
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});publicvoidonError(ANErrorerror) {
if (error.getErrorCode() != 0) {
// received error from server// error.getErrorCode() - the error code from server// error.getErrorBody() - the error body from server// error.getErrorDetail() - just an error detailLog.d(TAG, "onError errorCode : " + error.getErrorCode());
Log.d(TAG, "onError errorBody : " + error.getErrorBody());
Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
// get parsed error object (If ApiError is your class)ApiErrorapiError = error.getErrorAsObject(ApiError.class);
} else {
// error.getErrorDetail() : connectionError, parseError, requestCancelledErrorLog.d(TAG, "onError errorDetail : " + error.getErrorDetail());
}
}AndroidNetworking.evictBitmap(key); // remove a bitmap with key from LruCacheAndroidNetworking.evictAllBitmap(); // clear LruCacheAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "30")
.setTag(this)
.setPriority(Priority.LOW)
.build()
.prefetch();OkHttpClientokHttpClient = newOkHttpClient().newBuilder()
.addInterceptor(newGzipRequestInterceptor())
.build();
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.addHeaders("token", "1234")
.setTag("test")
.setPriority(Priority.LOW)
.setOkHttpClient(okHttpClient) // passing a custom okHttpClient
.build()
.getAsJSONArray(newJSONArrayRequestListener() {
@OverridepublicvoidonResponse(JSONArrayresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});ANRequest.GetRequestBuildergetRequestBuilder = newANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);
if(isHeaderRequired){
getRequestBuilder.addHeaders("token", "1234");
}
if(executorRequired){
getRequestBuilder.setExecutor(Executors.newSingleThreadExecutor());
}
ANRequestanRequest = getRequestBuilder.build(); anRequest.getAsJSONObject(newJSONObjectRequestListener() {
@OverridepublicvoidonResponse(JSONObjectresponse) {
// do anything with response
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
});// Adding ListenerAndroidNetworking.setConnectionQualityChangeListener(newConnectionQualityChangeListener() {
@OverridepublicvoidonChange(ConnectionQualitycurrentConnectionQuality, intcurrentBandwidth) {
// do something on change in connectionQuality
}
});
// Removing Listener AndroidNetworking.removeConnectionQualityChangeListener();
// Getting current ConnectionQualityConnectionQualityconnectionQuality = AndroidNetworking.getCurrentConnectionQuality();
if(connectionQuality == ConnectionQuality.EXCELLENT) {
// do something
} elseif (connectionQuality == ConnectionQuality.POOR) {
// do something
} elseif (connectionQuality == ConnectionQuality.UNKNOWN) {
// do something
}
// Getting current bandwidthintcurrentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWNAndroidNetworking.download(url,dirPath,fileName)
.setTag("downloadTest")
.setPriority(Priority.MEDIUM)
.build()
.setAnalyticsListener(newAnalyticsListener() {
@OverridepublicvoidonReceived(longtimeTakenInMillis, longbytesSent, longbytesReceived, booleanisFromCache) {
Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
Log.d(TAG, " bytesSent : " + bytesSent);
Log.d(TAG, " bytesReceived : " + bytesReceived);
Log.d(TAG, " isFromCache : " + isFromCache);
}
})
.setDownloadProgressListener(newDownloadProgressListener() {
@OverridepublicvoidonProgress(longbytesDownloaded, longtotalBytes) {
// do anything with progress
}
})
.startDownload(newDownloadListener() {
@OverridepublicvoidonDownloadComplete() {
// do anything after completion
}
@OverridepublicvoidonError(ANErrorerror) {
// handle error
}
}); Note : IfbytesSentorbytesReceivedis -1 , itmeansitisunknownAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
.addPathParameter("userId", "1")
.setTag(this)
.setPriority(Priority.LOW)
.setUserAgent("getAnUser")
.build()
.getAsOkHttpResponseAndParsed(newTypeToken<User>() {
}, newOkHttpResponseAndParsedRequestListener<User>() {
@OverridepublicvoidonResponse(ResponseokHttpResponse, Useruser) {
// do anything with okHttpResponse and user
}
@OverridepublicvoidonError(ANErroranError) {
// handle error
}
});ANRequestrequest = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
.addPathParameter("pageNumber", "0")
.addQueryParameter("limit", "3")
.build();
ANResponse<List<User>> response = request.executeForParsed(newTypeToken<List<User>>() {});
if (response.isSuccess()) {
List<User> users = responseTwo.getResult();
} else {
//handle error
} - First of all the server must send cache-control in header so that is starts working.
- Response will be cached on the basis of cache-control max-age,max-stale.
- If internet is connected and the age is NOT expired it will return from cache.
- If internet is connected and the age is expired and if server returns 304(NOT MODIFIED) it will return from cache.
- If internet is NOT connected if you are using getResponseOnlyIfCached() - it will return from cache even it date is expired.
- If internet is NOT connected , if you are NOT using getResponseOnlyIfCached() - it will NOT return anything.
- If you are using getResponseOnlyFromNetwork() , it will only return response after validation from server.
- If cache-control is set, it will work according to the max-age,max-stale returned from server.
- If internet is NOT connected only way to get cache Response is by using getResponseOnlyIfCached().
AndroidNetworking.enableLogging(); // simply enable loggingAndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level// Enabling GZIP for Request (Not needed if your server doesn't support GZIP Compression), anyway responses // from server are automatically unGzipped if required. So enable it only if you need your request to be // Gzipped before sending to server(Make sure your server support GZIP Compression).OkHttpClientokHttpClient = newOkHttpClient().newBuilder()
.addInterceptor(newGzipRequestInterceptor())
.build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient); Use IMMEDIATE Priority with caution - use is at appropriate place only when 1 or 2 (at max 2)IMMEDIATE request is required at instant.Otherwise use HIGH Priority.
Known Bug : As present if you are using GZIP Interceptor from client to server, Upload progress is not working perfectly in Multipart.
If you are using Proguard with Gradle build system (which is usually the case), you don't have to do anything. The appropriate Proguard rules will be automatically applied. If you still need the rules applied in
proguard-rules.pro, it is as follows:-dontwarn okio.**
- Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
- Fast Android Networking Library supports downloading any type of file
- Fast Android Networking Library supports uploading any type of file (supports multipart upload)
- Fast Android Networking Library supports cancelling a request
- Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
- Fast Android Networking Library supports RxJava
As it uses OkHttp as a networking layer, it supports:
- Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
- Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
- Transparent GZIP shrinks download sizes
- Fast Android Networking Library supports response caching which avoids the network completely for repeat requests
- In Fast Android Networking Library, OkHttpClient can be customized for every request easily.
- As Fast Android Networking Library uses OkHttp and Okio, it is faster.
- Single library for all type of networking.
- Supports RxJava, RxJava2 -> Check here
- Current bandwidth and connection quality can be obtained to decide logic of code.
- Executor can be passed to any request to get response in another thread.
- Complete analytics of any request can be obtained.
- All types of customization is possible.
- Immediate Request is really immediate now.
- Prefetching of any request can be done so that it gives instant data when required from cache.
- Proper cancellation of request.
- Do not cancel a request if completed more than a threshold percentage.
- Simple interface to make any type of request.
- Proper Response Caching, hence reducing bandwidth usage.
- Integration with other library
- And of course many many features and bug fixes
- Square - As both OkHttp and Okio used by Fast Android Networking is developed by Square.
- Volley - As Fast Android Networking uses ImageLoader that is developed by Volley.
- Prashant Gupta - For RxJava, RxJava2 Support - RxJava Support
###Check out Mindorks awesome open source projects here
Copyright (C) 2016 Amit Shekhar
Copyright (C) 2011 Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Just make pull request. You are in!
