博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AndroidAsync
阅读量:6158 次
发布时间:2019-06-21

本文共 7595 字,大约阅读时间需要 25 分钟。

hot3.png

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  (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

  • Based on NIO. One thread, driven by callbacks. Highly efficient.

  • All operations return a Future that can be cancelled

  • Socket client + socket server

  • HTTP client + server

  • WebSocket client + server

  • Socket.IO client

Download

Download  or grab via Maven:

    
com.koushikdutta.async
    
androidasync
    
(insert latest version)

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 bytesResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),                                  getFileStreamPath("asynccache"),                                  1024 * 1024 * 10);

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(ByteBufferList byteBufferList) {                System.out.println("I got some bytes!");                // note that this data has been read                byteBufferList.recycle();            }        });    }});

AndroidAsync also supports socket.io

SocketIOClient.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.

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().execute(post, new StringCallback() {    @Override    public void onCompleted(Exception e, AsyncHttpResponse source, String result) {        if (e != null) {            ex.printStackTrace();            return;        }        System.out.println("Server says: " + result);    }});

AndroidAsync also let's you create simple HTTP servers:

AsyncHttpServer server = new AsyncHttpServer();List
 _sockets = new ArrayList
();server.get("/", new HttpServerRequestCallback() {    @Override    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {        response.send("Hello!!!");    }});// listen on port 5000server.listen(5000);// browsing http://localhost:5000 will return Hello!!!

And WebSocket Servers:

server.websocket("/live", new WebSocketRequestCallback() {    @Override    public void onConnected(final WebSocket webSocket, RequestHeaders headers) {        _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!for (WebSocket socket : _sockets)    socket.send("Fireball!");

Futures

All the API calls return .

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

For brevity...

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

转载于:https://my.oschina.net/bv10000/blog/306104

你可能感兴趣的文章
android防止内存溢出浅析
查看>>
4.3.3版本之引擎bug
查看>>
SQL Server表分区详解
查看>>
STM32启动过程--启动文件--分析
查看>>
垂死挣扎还是涅槃重生 -- Delphi XE5 公布会归来感想
查看>>
淘宝的几个架构图
查看>>
linux后台运行程序
查看>>
Python异步IO --- 轻松管理10k+并发连接
查看>>
Oracle中drop user和drop user cascade的区别
查看>>
登记申请汇总
查看>>
Android Jni调用浅述
查看>>
CodeCombat森林关卡Python代码
查看>>
(二)Spring Boot 起步入门(翻译自Spring Boot官方教程文档)1.5.9.RELEASE
查看>>
Shell基础之-正则表达式
查看>>
JavaScript异步之Generator、async、await
查看>>
讲讲吸顶效果与react-sticky
查看>>
c++面向对象的一些问题1 0
查看>>
售前工程师的成长---一个老员工的经验之谈
查看>>
Get到的优秀博客网址
查看>>
老男孩教育每日一题-第107天-简述你对***的理解,常见的有哪几种?
查看>>