Android networking library can be used in an android application to send http request and fetch data online from server.
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
In this blog we have covered a curated list of top 5 such android networking libraries that can help you in performing networking requests.
OkHTTP Networking Library
OkHTTP is a HTTP Client networking library. It helps in exchanging data and other forms of media with online servers by sending requests.
What makes OkHttp an efficient library is that it helps in loading data faster and saves bandwidth. The library has more than 34,000 stars and 7400 forks at GitHub. Making it a choice of many great developer.
Features
Some features of OkHttp library are as follows:
- All requests to same hosts are made on the same socket, it helps in economic use of device resources and makes it more efficient.
- It pools the connection to reduce network latency.
- Shrinking download size is possible using Transparent GZIP so the content length is reduced.
- OkHttp supports response caching to reduce network request.
- If a particular IP Address fails in network request, OkHttps uses other IP Address to send network request.
- OkHttp supports both synchronous blocking calls and async calls with callbacks.
Implementing OkHttp in Project
To implement OkHttp in your Android Studio project, add the following lines to your build.gradle file:
implementation("com.squareup.okhttp3:okhttp:4.1.0")
Sending GET Request
Here is how you send a GET request in OkHttp:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Sending a POST Request
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Fast Android Networking Library
Fast Android Networking library is an advance version of OkHTTP Library.
Its build on the top of OkHttp. This makes it fast and efficient with added new features.
Features
- Fast Android Networking library is fast and easy to implement
- It provide all features of OkHttp Library
- It uses Okio, to handle garbage collection overhead while allocating memory. Okio does some clever things to save CPU and memory.
- Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
- Fast Android Library supports downloading any type of file.
- Fast Android Library supports uploading any type of file (supports multipart upload).
- Fast Android Library supports cancelling a request.
- Fast Android Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
- Fast Android Library supports RxJava
Implementing Fast Android Networking Library
implementation 'com.amitshekhar.android:android-networking:1.0.2'
Send GET Request
Initialize Library in onCreate()
AndroidNetworking.initialize(getApplicationContext());
Sending GET Request
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(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response | RETURN TO ONPOSTEXTEUTE()
}
@Override
public void onError(ANError error) {
// handle error
}
});
Making POST Request
Initialize library in onCreate()
AndroidNetworking.initialize(getApplicationContext());
Send POST Request
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
.addBodyParameter("firstname", "Amit")
.addBodyParameter("lastname", "Shekhar")
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
Downloading File Request
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 File Request
AndroidNetworking.upload(url)
.addMultipartFile("image",file)
.addMultipartParameter("key","value")
.setTag("uploadTest")
.setPriority(Priority.HIGH)
.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
}
});
Other Features
Enabling GZIP From Client to server
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).
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor(new GzipRequestInterceptor())
.build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);
Getting Analytics of a request
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
}
});
Connection listener to get quality of Network
// 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 Bitmap from url with some specified parameters
Great for Unsplash API, you can use the Android Networking Library to get Bitmap of a file from a specified URL and specify certain parameters like height, width of an image.
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
}
});
Loading image from network into ImageView
To load an image from network into the imageview widget, use the ANImageView widget in the activity XML file and the following Java code.
You can also see here how to download image from URL and requesting permissions
<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);
Cancelling a request
One can cancel a request by using following line of code:
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.
Not Cancelling a request if certain threshold is achieved
You can set a certain percentage of threshold so if its achieved then the request doesn’t get cancelled.
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(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
}
});
Volley Networking Library
Volley is an HTTP Networking Android Library that makes it faster and easier for developers to send request to servers from app.
Features
- Volley allows automatic scheduling of network requests
- It can maintain concurrent network requests
- It has support for request priotitization
- Allows to cancel a single or a block of request(s).
- Can be customized with extra features like backoff and retry.
- Supports Memory response caching to limit request sent to server.
- Supported ordering so data can be easily populated in the UI as the data is fetched asynchronously from the network.
- Has debugging and tracing tools.
- Volley frees you from writing boilerplate code and allows you to concentrate on the logic that is specific to your app.
However, Volley is not suitable for large download or streaming operations, since Volley holds all responses in memory during parsing. For large download operations, consider other libraries discussed in this blog.
Implementing Volley
Add volley implementation to your build.gradle android project dependencies
dependencies {
implementation 'com.android.volley:volley:1.1.1'
}
Sending GET Request
Using Volley Networking library you can send a GET request to server by creating a RequetQueue and passing it the Request objects.
The RequestQueue manages the worker thread for running network operations, reading and writing to cache and parsing the responses.
Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.
Read more about GET Requests from here.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
Cancel a Request
To cancel a request, call cancel() on your Request object.
public static final String TAG = "MyTag";
StringRequest stringRequest; // Assume this exists.
RequestQueue requestQueue; // Assume this exists.
// Set the tag on the request.
stringRequest.setTag(TAG);
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Learn more about RequestQueue from here.
Sending POST Request
This is how one can send a POST Request from Volley Networking library
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Retrofit Networking Library
Retrofit is a type-safe HTTP Client for Android and Java.
Type-Safe means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Implementing Retrofit
Add Retrofit, GSON and GSON Converter library to your project implementation
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Sending GET Request
For sending a GET request, Retrofit gives you the option of the synchronous and asynchronous HTTP request.
Depending on how you declare your interface method, it will either be synchronous or asynchronous HTTP Request.
public interface MyInterface {
// Synchronous declaration
@GET("/my_api/shop_list")
Response getMyThing1(@Query("mid") String param1);
// Asynchronous declaration
@GET("/my_api/shop_list")
void getMyThing2(@Query("mid") String param1, Callback<Response> callback);
}
To get access to the data received from the server is to map the JSON class to Java object and let Retrofit do the conversion.
Making a GET Request
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.apiurl.com/base/")
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(APIService.class);
Read more about Retrofit here.
Cornet Networking Library
Cronet android networking library is a framework that using chromium net to send network request for android.
For easy implementation we are using library forked by Lizhangqu.
Implementation
Add following lines of code to your build.gradle file
implementation 'io.github.lizhangqu:cronet-native:73.0.3653.0.5'
Sending GET Request
Sending GET request with other callbacks
UrlRequest.Builder builder = new UrlRequest.Builder(mEditTextUrl.getText().toString(), new UrlRequest.Callback() {
private ByteArrayOutputStream mBytesReceived = new ByteArrayOutputStream();
private WritableByteChannel mReceiveChannel = Channels.newChannel(mBytesReceived);
@Override
public void onRedirectReceived(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo, String s) throws Exception {
Log.i("TAG", "onRedirectReceived");
urlRequest.followRedirect();
}
@Override
public void onResponseStarted(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo) throws Exception {
Log.i("TAG", "onResponseStarted");
urlRequest.read(ByteBuffer.allocateDirect(32 * 1024));
}
@Override
public void onReadCompleted(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo, ByteBuffer byteBuffer) throws Exception {
Log.i("TAG", "onReadCompleted");
byteBuffer.flip();
try {
mReceiveChannel.write(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
byteBuffer.clear();
urlRequest.read(byteBuffer);
}
@Override
public void onSucceeded(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo) {
Log.i("TAG", "onSucceeded");
Log.i("TAG", String.format("Request Completed, status code is %d, total received bytes is %d",
urlResponseInfo.getHttpStatusCode(), urlResponseInfo.getReceivedBytesCount()));
final String receivedData = mBytesReceived.toString();
final String url = urlResponseInfo.getUrl();
final String text = "Completed " + url + " (" + urlResponseInfo.getHttpStatusCode() + ")";
Log.i("TAG", "text:" + text);
Log.i("TAG", "receivedData:" + receivedData);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "onSucceeded", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFailed(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo, UrlRequestException e) {
Log.i("TAG", "onFailed");
Log.i("TAG", "error is: %s" + e.getMessage());
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "onFailed", Toast.LENGTH_SHORT).show();
}
});
}
}, executor, cronetEngine);
builder.build().start();
Sending POST Request
public void startWithURL(String url, UrlRequest.Callback callback, Executor executor, String postData) {
UrlRequest.Builder builder = new UrlRequest.Builder(url, callback, executor, mCronetEngine);
applyPostDataToUrlRequestBuilder(builder, executor, postData);
builder.build().start();
}
private void applyPostDataToUrlRequestBuilder(
UrlRequest.Builder builder, Executor executor, String postData) {
if (postData != null && postData.length() > 0) {
builder.setHttpMethod("POST");
builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
builder.setUploadDataProvider(
UploadDataProviders.create(postData.getBytes()), executor);
}
}
And then reuse the callback in Send GET Request
1 comment