Easiest Way To Make REST API calls on Android Beginner Friendly with one line of Code (No Retrofit Needed)
In this post i will teach you how to make REST API Calls(GET,POST,…..), Upload Files, Download Files
If you are an experienced Android Developer or just a beginner making web request or API calls is has a big part to play in applications that read/write data over the internet.
With that out of the way, i formerly used Retrofit to do all my web requests. It was easy to use but i ran into a problem were i had a web request that returned a malformed JSON and i needed to get the response as a String and then sanitized the response before feeding it into a JSON parser. Sounds like a lot of steps huh! It was. 😄
Converter Factory (in my own simplest words): It tells Retrofit how to treat and parse the API response you get.
My first attempt was to use a string converter factory called (ScalarsConverterFactory)
with Retrofit to get the response as a string because using a GSON converter factory would throw a Malform JSON Exception or i’d i’ll need to create a custom Converter which i was not ready to. When i did the Response was encrypted so i needed an alternative with i will be sharing with you today.
Enough talk let’s dive into my second attempt.
I came across this library on Github that solved that problem and also enabled me to make API calls in one line of Code. 🎉🍾
The Library is called Fast-Android-Networking by amitshekhariitbhu
Requirements:
Fast Android Networking Library can be included in any Android application.
Fast Android Networking Library supports Android 2.3 (Gingerbread) and later.
- Import the Library to Android Studio via Gradle in your build.gradle file.
implementation ‘com.amitshekhar.android: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 Requests.
i) Making GET Requests.
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
}
@Override
public void onError(ANError error) {
// handle error
}
});
NOTE: The Tag you set here will be used if you want to say cancel a request.
ii) Making 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
}
});
You can also get Headers, Body Parameters and Most importantly you can define how you want your Response treated with having to use converters or having to build a custom converter.
You can getAsJSONObject,getAsString, or getAsObject( Custom Java Object You Create).
You can also post java object, json, file, etc in POST request like this.
User user = new User();
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(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
// do anything with response
}
@Override
public void onError(ANError error) {
// handle error
}
});
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("firstname", "Amit");
jsonObject.put("lastname", "Shekhar");
} catch (JSONException e) {
e.printStackTrace();
}
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
.addJSONObjectBody(jsonObject) // posting json
.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
}
});
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
.addFileBody(file) // posting any type of file
.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
}
});
Using it with your own JAVA Object — JSON Parser
/*--------------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, 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("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{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)
.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
}
});
Cancelling a request.
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.
That will be all for this tutorial. Theres a whole lot more you can do with this Library by amitshekhariitbhu. Try it out and let me know in the comments how it made your coding life easier. 👏 Follow Share 😁 to stay in the Loop. 👍