Android为咱们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然二者都支持HTTPS,流的上传和下载,配置超时,IPv6和链接池,已足够知足咱们各类HTTP请求的需求。但更高效的使用HTTP能够让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。html
OkHttp是一个高效的HTTP库:java
会从不少经常使用的链接问题中自动恢复。若是您的服务器配置了多个IP地址,当第一个IP链接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。android
使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection同样的API。若是您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。git
下面的示例请求一个URL并答应出返回内容字符.github
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; (count