PAC-ROM/android_external_koush_AndroidAsync

Name: android_external_koush_AndroidAsync

Owner: PAC-ROM

Description: null

Created: 2015-10-17 21:43:42.0

Updated: 2015-10-17 21:44:09.0

Pushed: 2015-10-20 00:02:22.0

Homepage: null

Size: 3768

Language: Java

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

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 client/server, WebSocket, and Socket.IO library for Android, AndroidAsync is it.

Features
Download

Download the latest JAR or grab via Maven:

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

Gradle:

ndencies {
compile 'com.koushikdutta.async:androidasync:2.+'

Download a url to a String
rl is the URL to download.
cHttpClient.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
rl is the URL to download.
cHttpClient.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…

rl is the URL to download.
cHttpClient.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
cHttpClient.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
rguments are the http client, the directory to store cache files, and the size of the cache in bytes
onseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),
                              getFileStreamPath("asynccache"),
                              1024 * 1024 * 10);
Can also create web sockets:
cHttpClient.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 supports socket.io (version 0.9.x)
etIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://192.168.1.2:3000", new ConnectCallback() {
@Override
public void onConnectCompleted(Exception ex, SocketIOClient client) {
    if (ex != null) {
        ex.printStackTrace();
        return;
    }
    client.setStringCallback(new StringCallback() {
        @Override
        public void onString(String string) {
            System.out.println(string);
        }
    });
    client.on("someEvent", new EventCallback() {
        @Override
        public void onEvent(JSONArray argument, Acknowledge acknowledge) {
            System.out.println("args: " + arguments.toString());
        }
    });
    client.setJSONCallback(new JSONCallback() {
        @Override
        public void onJSON(JSONObject json) {
            System.out.println("json: " + json.toString());
        }
    });
}

Need to do multipart/form-data uploads? That works too.
cHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
ipartFormDataBody body = new MultipartFormDataBody();
.addFilePart("my-file", new File("/path/to/file.txt");
.addStringPart("foo", "bar");
.setBody(body);
cHttpClient.getDefaultInstance().execute(post, new StringCallback() {
@Override
public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
    if (ex != null) {
        ex.printStackTrace();
        return;
    }
    System.out.println("Server says: " + result);
}

AndroidAsync also let's you create simple HTTP servers:
cHttpServer server = new AsyncHttpServer();

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

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


isten on port 5000
er.listen(5000);
rowsing http://localhost:5000 will return Hello!!!
And WebSocket Servers:
er.websocket("/live", new 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", "Error");
            } 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!
(WebSocket socket : _sockets)
socket.send("Fireball!");
Futures

All the API calls return Futures.

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

Futures can also have callbacks…

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

For brevity…

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

Note on SSLv3

https://github.com/koush/AndroidAsync/issues/174


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.