原文章:http://www.koushikdutta.com/AndroidAsync
AndroidAsync
AndroidAsync是一个低级别的网络协议库。如果你在找一个容易使用,高级别,Android软件,http请求库,可查看Ion库(它建立在AndroidAsync之上)。标准的Android开发人员对Ion可能更感兴趣。
但是如果你在找一个原生的socket。http 客户端/服务器,WebSocket,和Socket。那Android的IO流库,AndroidAsync就是你要找的。
特点:
1. 基于NIO。一个线程,有回调驱动。高性能。
2. 所有的操作都返回一个能取消的Future。
3. Socket 客户端+ Socket 服务端。
4. HTTP 客户端+服务端。
5. WebSocket 客户端+服务端。
6. Socket.IO 客户端。
下载:
下载最新的jar文件(https://search.maven.org/remote_content?g=com.koushikdutta.async&a=androidasync&v=LATEST )或者通过Maven抓取。
<dependency>
<groupId>com.koushikdutta.async</groupId>
<artifactId>androidasync</artifactId>
<version>(insert latest version)</version>
</dependency>
Gradle配置:
dependencies {
compile 'com.koushikdutta.async:androidasync:2.+'
}
下载url地址返回字符串类型
// url是下载的URL地址。
AsyncHttpClient.getDefaultInstance().getString(url, new AsyncHttpClient.StringCallback() {
// 如果可能,任何异常错误、结果都会请求回调
@Override
public void onCompleted(Exception e, AsyncHttpResponse response, String result) {
if (e != null) {
e.printStackTrace();
return;
}
System.out.println("I got a string: " + result);
}
});
从url地址下载得到JSON串。
// 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);
}
});
或者得到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);
}
});
下载url地址得到一个文件。
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());
}
});
同时也支持缓存。
// arguments are the http client, the directory to store cache files, and the size of the cache in bytes参数是http客户端请求,存储缓存文件地址,和缓存的字节大小。
ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),getFileStreamPath("asynccache"),1024 * 1024 * 10);
也可以创建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也支持socket.io(0.9.x版本)
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());
}
});
}
});
需要上传多文件表单数据?它同样可以。
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 ex, AsyncHttpResponse source, String result) {
if (ex != null) {
ex.printStackTrace();
return;
}
System.out.println("Server says: " + result);
}
});
AndroidAsync同样可以让你创建简单的http服务。
```java 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!!!
```
和WebSocket Servers:
```java server.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! for (WebSocket socket : _sockets) socket.send("Fireball!"); ```
特点:
所有的API请求都返回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同样可以回调。
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);
}
});
简短概括:
client.getString("http://foo.com/hello.txt")
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
System.out.println(result);
}
});