Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。
OkHttp是一个高效的HTTP库:
- 支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
- 如果SPDY不可用,则通过连接池来减少请求延时
- 无缝的支持GZIP来减少数据流量
- 缓存响应数据来减少重复的网络请求
会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。
Examples
下面的示例请求一个URL并答应出返回内容字符.
package com.squareup.okhttp.guide; import com.squareup.okhttp.OkHttpClient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class GetExample { OkHttpClient client = new OkHttpClient(); void run() throws IOException { String result = get(new URL("https://raw.github.com/square/okhttp/master/README.md")); System.out.println(result); } 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(); } } byte[] readFully(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int count