An android asynchronous http client built on top of HttpURLConnection.

Overview

Versions

Version 1.0.6

Description

An android asynchronous http client based on HttpURLConnection.

Updates

  • Use of java Future object to allow optional blocking of current thread until the asynchronous http client returns results.

Getting Started

Add the dependency in build.gradle (App module)

compile 'com.eukaprotech.networking:networking:1.0.6@aar'

Add permission in manifest file

<uses-permission android:name="android.permission.INTERNET" />

Request Methods Covered

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • OPTIONS

GET request:

AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.get("url", new AsyncConnectionHandler() { 
    @Override
    public void onStart() {
       //you can choose to show a progress bar here.
    }

    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, byte[] response) {
        //consume the success response here.
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        //consume the fail response here
    }

    @Override
    public void onComplete() {
       //you can dismiss the progress bar here.
    }
});

Sample GET request:

AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.get("https://www.google.com", new AsyncConnectionHandler() { 
    @Override
    public void onStart() {
       //you can choose to show a progress bar here.
    }

    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, byte[] response) {
        //consume the success response here.
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        //consume the fail response here.
    }

    @Override
    public void onComplete() {
       //you can dismiss the progress bar here.
    }
});

Sample Blocking GET request:

The AsyncConnection http method calls return a Future object which handles a result of type HashMap<String, Object>. If you want to block the current thread until you get the result, call the get() function of the Future object as shown below. Note the difference between the http get() and the blocking get() function.

AsyncConnection asyncConnection = new AsyncConnection();
HashMap<String, Object> map = asyncConnection.get("https://www.google.com", new AsyncConnectionHandler() { 
    @Override
    public void onStart() {
       //you can choose to show a progress bar here.
    }

    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, byte[] response) {
        //consume the success response here.
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        //consume the fail response here.
    }

    @Override
    public void onComplete() {
       //you can dismiss the progress bar here.
    }
}).get();// the blocking call. 

OR

AsyncConnection asyncConnection = new AsyncConnection();
HashMap<String, Object> map = asyncConnection.get("https://www.google.com", null).get();// the blocking call. 

The HashMap<String, Object> contains the following key-value pairs:

status: String //"success" or "fail
responseCode: integer 
headers: HashMap<String, String>
response: byte[]
error: Exception

File Download Handler

A File download handler, FileAsyncConnectionHandler, is used to directly write a connection response to a file:

asyncConnection.get("url", new FileAsyncConnectionHandler() {
    @Override
    public void onStart() {
        //you can choose to show a progress bar here.
    }

    @Override
    public String onGetFileAbsolutePath(String contentType) {
        //you can determine the file-extension to use based on contentType
        File file = new File("path");
        return file.getAbsolutePath();
    }

    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, File response) {
        //the response is the file whose path you provided. You can use the file at this point
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        
    }

    @Override
    public void onComplete() {
        //you can dismiss the progress bar here.
    }
});

Query Parameters

To attach query parameters to a url:

Parameters query_parameters = new Parameters();
query_parameters.put("key1", "value1");
query_parameters.put("key2", "value2");

String url = URLBuilder.build("initial_url", query_parameters);
//if the initial_url already contains query parameters, the new query parameters are just added at the end of existing ones.
//in case of conflicting keys between the existing query parameters and the new ones; the new ones are given priority.
//you can then use the resulting url in a request

Sample:

Parameters query_parameters = new Parameters();
query_parameters.put("q", "discover");
String url = URLBuilder.build("https://www.google.com/search", query_parameters);
//will result into https://www.google.com/search?q=discover
//you can then use the resulting url in a request

AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.get(url, new AsyncConnectionHandler() {
    // the implemented listener functions onStart, onSucceed, onFail & onComplete
});

Body Parameters (Used for POST & PUT)

To attach parameters as the body/content of the request

Parameters parameters = new Parameters();
parameters.put("key1", "value1");
parameters.put("key2", "value2");

//For a POST request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.post("url", parameters, new AsyncConnectionHandler() {  
    // the implemented listener functions here. 
});

//For a PUT request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.put("url", parameters, new AsyncConnectionHandler() {  
    // the implemented listener functions here. 
});

Request Headers

To attach request headers:

HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "basicAuth value");
Parameters parameters = new Parameters();
parameters.put("key1", "value1");
parameters.put("key2", "value2");

//For a POST request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.post("url", headers, parameters, new AsyncConnectionHandler() { 
    // the implemented listener functions here. 
});

//For a GET request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.get("url", headers, new AsyncConnectionHandler() { 
    // the implemented listener functions here.  
});
//Other request methods have similar way of attaching request headers

Body JSONObject (Used for POST & PUT)

JSONObject can be used in place of Parameters as the body/content of the request:

JSONObject jsonObject = new JSONObject();
try{
    jsonObject.put("key1", "value1");
    jsonObject.put("key2", "value2");
}catch (Exception ex){}

HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");    //header for JSONObject being the body/content

//For a POST request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.post("url", headers, jsonObject, new AsyncConnectionHandler() {  
    // the implemented listener functions here.
});

//For a PUT request
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.put("url", headers, jsonObject, new AsyncConnectionHandler() {  
    // the implemented listener functions here.
});

Basic Authentication

To attach a basic auth in the request headers:

Method 1: (Handle it)

HashMap<String, String> headers = new HashMap<>();
String username = "[email protected]"; 
String password = "123456789";
String auth_value = username+":"+password;
String basicAuth = "basic "+ Base64.encodeToString(auth_value.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", basicAuth);

Method 2: (Let AsyncConnection handle it)

String username = "[email protected]"; 
String password = "123456789";
AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.setBasicAuthentication(username, password); 

Track the Upload and Download Progress of a Single Connection

Both handlers, AsyncConnectionHandler and FileAsyncConnectionHandler have functions to track the upload and download progress of a connection. These functions are onUploadProgressUpdate and onDownloadProgressUpdate. The functions are optional; you can choose to implement them or not.

Tracking upload and download progress with AsyncConnectionHandler:

asyncConnection.post("url", parameters, new AsyncConnectionHandler() {// you can use any http method other than POST
    @Override
    public void onStart() {
        //you can choose to show a progress bar here.
    }
    
    @Override
    public void onUploadProgressUpdate(long progress, long length) {
        //length is the total size of the content/parameters being uploaded or written to the connection.
        //You can use a determinate progress bar at this point.
    }

    @Override
    public void onDownloadProgressUpdate(long progress, long length) {
        //length is the total size of the content being downloaded or read from the connection.
        //NOTE: length depends on the server returning a content-length header. 
        //If the server returns chunked transfer-encoding header, content-length header is not available, the length is unknown 
        //When the length is not known, the value of length will be -1.
        //If length is -1, avoid displaying a determinate progress bar.
    }
    
    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, byte[] response) {
        
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        
    }

    @Override
    public void onComplete() {
        //you can dismiss the progress bar here.
    }
});

Tracking upload and download progress with FileAsyncConnectionHandler:

asyncConnection.post("url", parameters, new FileAsyncConnectionHandler() {// you can use any http method other than POST
    @Override
    public void onStart() {
        //you can choose to show a progress bar here.
    }
    
    @Override
    public void onUploadProgressUpdate(long progress, long length) {
        //length is the total size of the content/parameters being uploaded or written to the connection.
        //You can use a determinate progress bar at this point.
    }

    @Override
    public void onDownloadProgressUpdate(long progress, long length) {
        //length is the total size of the content being downloaded or read from the connection.
        //NOTE: length depends on the server returning a content-length header. 
        //If the server returns chunked transfer-encoding header, content-length header is not available, the length is unknown 
        //When the length is not known, the value of length will be -1.
        //If length is -1, avoid displaying a determinate progress bar.
    }

    @Override
    public String onGetFileAbsolutePath(String contentType) {
        
    }

    @Override
    public void onSucceed(int responseCode, HashMap<String, String> headers, File response) {
        
    }

    @Override
    public void onFail(int responseCode, HashMap<String, String> headers, byte[] response, Exception error) {
        
    }

    @Override
    public void onComplete() {
        //you can dismiss the progress bar here.
    }
});

Track the Upload and Download Progress of Multiple Connections

MultipleAsyncConnections multipleAsyncConnections = new MultipleAsyncConnections();
List<AsyncConnection> asyncConnectionList = multipleAsyncConnections.generateConnections(2);
// 2 is the number of connections you desire to monitor
AsyncConnection asyncConnection1 = asyncConnectionList.get(0);
AsyncConnection asyncConnection2 = asyncConnectionList.get(1);
        
asyncConnection1.post("url", parameters1, new AsyncConnectionHandler() {// you can use any http method other than POST
    // the implemented listener functions here
});
asyncConnection2.post("url", parameters2, new FileAsyncConnectionHandler() {// you can use any http method other than POST
    // the implemented listener functions here
});

//For Connections generated by MultipleAsyncConnections to start processing;
multipleAsyncConnections.startConnections(new MultipleAsyncConnectionsHandler() {
    @Override
    public void onStart() {
        //called once when connections start.
        //you can choose to show a progress bar here.
    }

    @Override
    public void onUploadProgressUpdate(long progress, long length) {
        //progress is the cumulative size uploaded across all the connections being tracked
        //length is the cumulative total size to be uploaded across all the connections being tracked
        //You can use a determinate progress at this point.
    }

    @Override
    public void onDownloadProgressUpdate(long progress, long length) {
        //progress is the cumulative size downloaded across all the connections being tracked
        //length is the cumulative total size to be downloaded across all the connections being tracked
        //NOTE: length depends on the server returning a content-length header to each of the connections being tracked. 
        //If the server returns chunked transfer-encoding header, content-length header is not available, the length is unknown 
        //When the length is not known, the cumulative value of length across the connections will not be useful.
        //Avoid displaying a determinate progress bar here at all.
    }

    @Override
    public void onComplete() {
        //called once when all connections complete.
        //you can dismiss the progress bar here.
    }
});

Uploading Files

To upload a File, include it in the body parameters

File file = new File("file path");
Parameters parameters = new Parameters();
try {
    parameters.put("key1", file);
} catch (IOException e) {

}
parameters.put("key2", "value2");

Uploading Array of Files

To upload array of files, include the array in the body parameters

File file1 = new File("file path1");
File file2 = new File("file path2");

Parameters parameters = new Parameters();
File[] arrayFiles = new File[]{file1, file2};
try {
    parameters.put("key1", arrayFiles);
} catch (IOException e) {

}
parameters.put("key2", "value2");

Uploading Files Whose Content is Your Bytes or InputStream

A class named FileItem is used. Note that parameters of value FileItem are uploaded to the server just like any other file; difference being that the content is read from the bytes or inputstream you provide.

To upload a file with your own bytes as content, include it as a FileItem in the body parameters.

byte[] bytes = "Hey there".getBytes();
FileItem fileItem = new FileItem("sample.txt", bytes); // "sample.txt" is the file name which must not be a name of an existing file
Parameters parameters = new Parameters();
parameters.put("key1", fileItem);
parameters.put("key2", "value2");

To upload a file with your own InputStream as content, include it as a FileItem in the body parameters

InputStream inputStream = null;
File file = new File("file path"); //must be a path of an existing file
try {
    inputStream = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
long length = file.length();
FileItem fileItem = new FileItem("index.html", length, inputStream); //the length is important for progress monitoring, "index.html" is the file name which must not be a name of an existing file
Parameters parameters = new Parameters();
parameters.put("key1", fileItem);
parameters.put("key2", "value2");

To upload array of files with your own bytes or InputStream as content, include them as array of FileItem in the body parameters

byte[] bytes = "Hey there".getBytes();
FileItem fileItem1 = new FileItem("sample.txt", bytes);

InputStream inputStream = null;
File file = new File("file path"); //must be a path of an existing file
try {
    inputStream = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
long length = file.length();
FileItem fileItem2 = new FileItem("index.html", length, inputStream);

FileItem[] arrayFiles = new FileItem[]{fileItem1, fileItem2};
Parameters parameters = new Parameters();
parameters.put("key1", arrayFiles);
parameters.put("key2", "value2");

Uploading Bytes

To upload bytes, include them as BytesItem in the body parameters

Parameters parameters = new Parameters();
byte[] bytes = "Hey bytes".getBytes()// your bytes here;
parameters.put("key1", new BytesItem(bytes));
parameters.put("key2", "value2");

Provide Your InputStream for Upload

To provide your own inputstream, include it as an InputStreamItem in the body parameters. An example of using an input stream from a file:

Parameters parameters = new Parameters();
InputStream inputStream = null;
File file = new File("file path"); //must be a path of an existing file
try {
    inputStream = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {

}
long length = file.length();
parameters.put("key1", new InputStreamItem(length, inputStream));
parameters.put("key2", "value2");

An example of using an input stream of bytes:

Parameters parameters = new Parameters();
byte[] bytes = "Hey bytes".getBytes();
InputStream inputStream = new ByteInputStream(bytes);
long length = bytes.length;
parameters.put("key1", new InputStreamItem(length, inputStream));
parameters.put("key2", "value2");

Redirects

By default AsyncConnection does not follow redirects to different protocols such as HTTP to HTTPS or HTTPS to HTTP. To enable protocol shift redirects:

AsyncConnection asyncConnection = new AsyncConnection();
asyncConnection.setFollowProtocolShiftRedirects(true);

Setting Time Out

AsyncConnection asyncConnection = new AsyncConnection();
int time_out_in_milliseconds = 5000;
asyncConnection.setTimeOut(time_out_in_milliseconds);

NOTE

To consume the byte array response as a String:

String responseBody = new String(response); //OR
String responseBody = new String(response, "UTF-8");

Download

You might also like...
Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: !-- Pull in as a traditional dependency -- dependency groupIdcom.konghq/groupId artifactIdunire

Repo of the Open Source Android library : RoboSpice. RoboSpice is a modular android library that makes writing asynchronous long running tasks easy. It is specialized in network requests, supports caching and offers REST requests out-of-the box using extension modules. Android Asynchronous Networking and Image Loading
Android Asynchronous Networking and Image Loading

Android Asynchronous Networking and Image Loading Download Maven Git Features Kotlin coroutine/suspend support Asynchronously download: Images into Im

Easy, asynchronous, annotation-based SOAP for Android

IceSoap IceSoap provides quick, easy, asynchronous access to SOAP web services from Android devices. It allows for SOAP responses to be bound to Java

Write your asynchronous Network / IO call painlessly in Kotlin !!
Write your asynchronous Network / IO call painlessly in Kotlin !!

Asynkio : Write asynced IO/ Network calls painlessly on android | | | Documentation Write your network requests, IO calls in android with Kotlin seaml

 Ktor-Client  this is the client part that uses the Ktor server
Ktor-Client this is the client part that uses the Ktor server

Ktor-Client this is the client part that uses the Ktor server Previews Tech stack & Open source libraries Minimum SDK level 21. Kotlin+ Coroutines + F

Simple kafka client for monitoring topic events. Client has UI powered by Darklaf
Simple kafka client for monitoring topic events. Client has UI powered by Darklaf

kafka-client Simple kafka client for monitoring topic values. How to start $ java -jar kafka-client-1.0.jar How to use specify kafka hosts in config.y

Kotlin-echo-client - Echo client using Kotlin with Ktor networking library
Kotlin-echo-client - Echo client using Kotlin with Ktor networking library

Overview This repository contains an echo server implemented with Kotlin and kto

HTTP Server for Android Instrumentation tests

RESTMock REST API mocking made easy. RESTMock is a library working on top of Square's okhttp/MockWebServer. It allows you to specify Hamcrest matchers

Comments
  • Uploading a Base64. Error 'Payload Too Large'

    Uploading a Base64. Error 'Payload Too Large'

    Trying to upload an image as Base64 (268792 chars length, is not a huge one) gives me Payload Too Large error.

    I was working with another lib but decided to use yours, previous lib worked fine the upload, but was missing status codes and errors when failing.

    Server in NodeJS w/ Express is prepared to receive huge files (up to 50 Mb).

    Now, the POST request don't even reach the server side.

    Any solution?

    opened by carlosen14 3
  • When onComplete() is called ?

    When onComplete() is called ?

    Hello,

    Thank you for creating such nice library. I want to know if onFail() called then onComplete() will be called or not ? Please help with information.

    Advanced Thanks, Walioulislam

    opened by walioul 1
Owner
David
Software Developer
David
Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Koushik Dutta 7.3k Jan 2, 2023
Asynchronous Http and WebSocket Client library for Java

Async Http Client Follow @AsyncHttpClient on Twitter. The AsyncHttpClient (AHC) library allows Java applications to easily execute HTTP requests and a

AsyncHttpClient 6k Jan 8, 2023
Android Easy Http - Simplest android http request library.

Android Easy Http Library 繁體中文文檔 About Android Easy Http Library Made on OkHttp. Easy to do http request, just make request and listen for the respons

null 13 Sep 30, 2022
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

OkHttp See the project website for documentation and APIs. HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP

Square 43.4k Jan 5, 2023
A type-safe HTTP client for Android and the JVM

Retrofit A type-safe HTTP client for Android and Java. For more information please see the website. Download Download the latest JAR or grab from Mave

Square 41k Jan 5, 2023
Ktorfit - a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit

Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit

Jens Klingenberg 637 Dec 25, 2022
Multiplatform coroutine-based HTTP client wrapper for Kotlin

networkinkt This is a lightweight HTTP client for Kotlin. It relies on coroutines on both JS & JVM platforms. Here is a simple GET request: val text =

Egor Zhdan 31 Jul 27, 2022
Kotlin DSL http client

Introduction Kotlin DSL http client Features ?? Developers Experience-driven library without verbosity. ?? Native way to use http client in Kotlin. ??

Sergei Rybalkin 461 Dec 13, 2022
Unirest in Java: Simplified, lightweight HTTP client library.

Unirest for Java Install With Maven: <!-- Pull in as a traditional dependency --> <dependency> <groupId>com.konghq</groupId> <artifactId>unire

Kong 2.4k Jan 5, 2023