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