A very simple way to do http requests in Android using okHttp
- Create an instance of HttpBuster with an api endpoint
Api api = new Api();
api.setEndpoint("https://example.com/api/");
HttpBuster httpBuster = HttpBuster.withApi(api).build();
Thats it. Now you are ready to make http requests to your api endpoint.
a.) Without any request parameters
httpBuster.makeGetRequest("jokes/random", null, new ApiCallback() {
@Override
public void done(BusterResponse response, JSONObject jsonObject, Exception exception) {
Log.e(TAG, "GET without params done");
}
});
b.) With request parameters
HashMap<String, Object> map = new HashMap<>();
map.put("firstName", "Mutinda");
map.put("lastName", "Boniface");
httpBuster.makeGetRequest("jokes/random", map, new ApiCallback() {
@Override
public void done(BusterResponse response, JSONObject jsonObject, Exception exception) {
Log.e(TAG, "GET with params done");
}
});
- The same applies for
POST
,PUT
,DELETE
requests - We recommend using a single HttpBuster instance for the entire application- You can do this by intializing your HttpBuster instance via the Application class
// Add files to be upload
List<RequestFile> files = new ArrayList<>();
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"/no_picture.png";
files.add( new RequestFile("photo", file, MediaType.parse("image/PNG")) );
// add optional payload (this is optional)
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Mutinda Boniface");
httpBuster.makeMultipartRequest("photo-upload/", map, files, new ApiCallback() {
@Override
public void done(BusterResponse response, JSONObject jsonObject, Exception exception) {
Log.e(TAG, "POST MULTIPART - Response =" +(response!=null? response.getString() :"Not reachable" ));
}
});
Have a look at the demo app for a complete app using the Library Demo app
In your app build.gradle
under repositories, include jitpack.io
like below
allprojects{
repositories {
maven { url "https://jitpack.io" }
}
}
Then in your dependecies add this line replacing {latest_version} with the latest version under releases
compile 'com.github.bmutinda:httpbuster:{latest_version}'
Example:
compile 'com.github.bmutinda:httpbuster:1.0'
If HttpBuster
helped you save time for your project delivery, you can buy coffee for me. Cheers