AndroidAsync

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

License

License

GroupId

GroupId

com.koushikdutta.async
ArtifactId

ArtifactId

androidasync
Last Version

Last Version

3.1.0
Release Date

Release Date

Type

Type

aar
Description

Description

AndroidAsync
Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.
Project URL

Project URL

https://github.com/koush/AndroidAsync

Download androidasync

How to add to project

<!-- https://jarcasting.com/artifacts/com.koushikdutta.async/androidasync/ -->
<dependency>
    <groupId>com.koushikdutta.async</groupId>
    <artifactId>androidasync</artifactId>
    <version>3.1.0</version>
    <type>aar</type>
</dependency>
// https://jarcasting.com/artifacts/com.koushikdutta.async/androidasync/
implementation 'com.koushikdutta.async:androidasync:3.1.0'
// https://jarcasting.com/artifacts/com.koushikdutta.async/androidasync/
implementation ("com.koushikdutta.async:androidasync:3.1.0")
'com.koushikdutta.async:androidasync:aar:3.1.0'
<dependency org="com.koushikdutta.async" name="androidasync" rev="3.1.0">
  <artifact name="androidasync" type="aar" />
</dependency>
@Grapes(
@Grab(group='com.koushikdutta.async', module='androidasync', version='3.1.0')
)
libraryDependencies += "com.koushikdutta.async" % "androidasync" % "3.1.0"
[com.koushikdutta.async/androidasync "3.1.0"]

Dependencies

There are no dependencies for this project. It is a standalone project that does not depend on any other jars.

Project Modules

There are no modules declared in this project.

AndroidAsync

AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request library, check out Ion (it is built on top of AndroidAsync). The typical Android app developer would probably be more interested in Ion.

But if you're looking for a raw Socket, HTTP(s) client/server, and WebSocket library for Android, AndroidAsync is it.

Features

  • Based on NIO. Single threaded and callback driven.
  • All operations return a Future that can be cancelled
  • Socket client + socket server
  • HTTP client + server
  • WebSocket client + server

Download

Download the latest JAR or grab via Maven:

<dependency>
    <groupId>com.koushikdutta.async</groupId>
    <artifactId>androidasync</artifactId>
    <version>(insert latest version)</version>
</dependency>

Gradle:

dependencies {
    compile 'com.koushikdutta.async:androidasync:2.+'
}

Download a url to a String

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getString(url, new AsyncHttpClient.StringCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, String result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a string: " + result);
    }
});

Download JSON from a url

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getJSONObject(url, new AsyncHttpClient.JSONObjectCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, JSONObject result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a JSONObject: " + result);
    }
});

Or for JSONArrays...

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getJSONArray(url, new AsyncHttpClient.JSONArrayCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, JSONArray result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a JSONArray: " + result);
    }
});

Download a url to a file

AsyncHttpClient.getDefaultInstance().getFile(url, filename, new AsyncHttpClient.FileCallback() {
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, File result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("my file is available at: " + result.getAbsolutePath());
    }
});

Caching is supported too

// arguments are the http client, the directory to store cache files,
// and the size of the cache in bytes
ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),
                                  getFileStreamPath("asynccache"),
                                  1024 * 1024 * 10);

Need to do multipart/form-data uploads? That works too.

AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
MultipartFormDataBody body = new MultipartFormDataBody();
body.addFilePart("my-file", new File("/path/to/file.txt");
body.addStringPart("foo", "bar");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback(){
        @Override
        public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
            if (ex != null) {
                ex.printStackTrace();
                return;
            }
            System.out.println("Server says: " + result);
        }
    });

Can also create web sockets:

AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
    @Override
    public void onCompleted(Exception ex, WebSocket webSocket) {
        if (ex != null) {
            ex.printStackTrace();
            return;
        }
        webSocket.send("a string");
        webSocket.send(new byte[10]);
        webSocket.setStringCallback(new StringCallback() {
            public void onStringAvailable(String s) {
                System.out.println("I got a string: " + s);
            }
        });
        webSocket.setDataCallback(new DataCallback() {
            public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
                System.out.println("I got some bytes!");
                // note that this data has been read
                byteBufferList.recycle();
            }
        });
    }
});

AndroidAsync also let's you create simple HTTP servers:

AsyncHttpServer server = new AsyncHttpServer();

List<WebSocket> _sockets = new ArrayList<WebSocket>();

server.get("/", new HttpServerRequestCallback() {
    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send("Hello!!!");
    }
});

// listen on port 5000
server.listen(5000);
// browsing http://localhost:5000 will return Hello!!!

And WebSocket Servers:

AsyncHttpServer httpServer = new AsyncHttpServer();

httpServer.listen(AsyncServer.getDefault(), port);

httpServer.websocket("/live", new AsyncHttpServer.WebSocketRequestCallback() {
    @Override
    public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
        _sockets.add(webSocket);
        
        //Use this to clean up any references to your websocket
        webSocket.setClosedCallback(new CompletedCallback() {
            @Override
            public void onCompleted(Exception ex) {
                try {
                    if (ex != null)
                        Log.e("WebSocket", "An error occurred", ex);
                } finally {
                    _sockets.remove(webSocket);
                }
            }
        });
        
        webSocket.setStringCallback(new StringCallback() {
            @Override
            public void onStringAvailable(String s) {
                if ("Hello Server".equals(s))
                    webSocket.send("Welcome Client!");
            }
        });
    
    }
});

//..Sometime later, broadcast!
for (WebSocket socket : _sockets)
    socket.send("Fireball!");

Futures

All the API calls return Futures.

Future<String> string = client.getString("http://foo.com/hello.txt");
// this will block, and may also throw if there was an error!
String value = string.get();

Futures can also have callbacks...

Future<String> string = client.getString("http://foo.com/hello.txt");
string.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

For brevity...

client.getString("http://foo.com/hello.txt")
.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

Versions

Version
3.1.0
3.0.9
3.0.8
3.0.1
3.0.0
2.2.1
2.2.0
2.1.9
2.1.8
2.1.7
2.1.6
2.1.5
2.1.4
2.1.3
2.1.2
2.1.1
2.1.0
2.0.9
2.0.8
2.0.7
2.0.6
2.0.5
2.0.4
2.0.3
2.0.2
2.0.1
2.0.0
1.4.1
1.4.0
1.3.9
1.3.8
1.3.7
1.3.6
1.3.5
1.3.4
1.3.3
1.3.2
1.3.1
1.3.0
1.2.9
1.2.8
1.2.6
1.2.5
1.2.4
1.2.3
1.2.2
1.2.1
1.2.0
1.1.9
1.1.8
1.1.6
1.1.5
1.1.4
1.1.3
1.1.2
1.1.1
1.1.0
1.0.9
1.0.8
1.0.7
1.0.6
1.0.5
1.0.3
1.0.2
1.0.1
1.0.0