原文链接:
http://blog.chengyunfeng.com/?p=489
我们通过HTTP在设备和服务器之前交换数据。高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生
OkHttp是一个高效的HTTP库:
- 支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
- 如果SPDY不可用,则通过连接池来减少请求延时
- 无缝的支持GZIP来减少数据流量
- 缓存响应数据来减少重复的网络请求
OkHttp 处理了很多网络疑难杂症:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。
OkHttp 支持 Android 2.2+;Java 1.5+。
示例
通过GET请求一个URL
下面的示例请求一个URL并答应出返回内容字符。 猛击我查看全部代码
OkHttpClient client = new OkHttpClient();
String get(URL url) throws IOException {
HttpURLConnection connection = client.open(url);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null) in.close();
}
}
POST 数据到服务器
下面的代码通过Post发送数据到服务器 猛击我查看全部代码
OkHttpClient client = new OkHttpClient();
String post(URL url, byte[] body) throws IOException {
HttpURLConnection connection = client.open(url);
OutputStream out = null;
InputStream in = null;
try {
// Write the request.
connection.setRequestMethod("POST");
out = connection.getOutputStream();
out.write(body);
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
in = connection.getInputStream();
return readFirstLine(in);
} finally {
// Clean up.
if (out != null) out.close();
if (in != null) in.close();
}
}
项目主页: OkHttp