Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 網絡框架 OkHttp 學習指南

編輯:Android 資訊

OkHttp

OkHttp 是 Android 版的 Http 客戶端,非常高效,支援 SPDY、連接池、GZIP 和 HTTP 緩存。默認情況下,OkHttp 會自動處理常見的網絡問題,像二次連接、SSL 握手問題。如果你的應用集成了 OkHttp,Retrofit 默認也會使用 OkHttp 處理其他網絡層請求。

An HTTP & SPDY client for Android and Java applications。從 Android 4.4 開始,HttpURLConnection 的底層實現採用的就是 OkHttp。

使用要求:Android 需 2.3 以上,Java 需 7 以上。兩個模塊:okhttp-urlconnection 實現 HttpURLConnection API;okhttp-apache 實現 Apache HttpClient API。依賴 okio(https://github.com/square/okio):OkHttp 用它來實現快速 I/O 和可伸縮緩衝區。

安裝

maven:

com.squareup.okhttp
okhttp
2.3.0

Gradle:

compile 'com.squareup.okhttp:okhttp:2.3.0'

GET A URL

同步 GET:

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }
    System.out.println(response.body().string());
}

異步 GET:

在一個工作線程中下載文件,當響應可讀時回調 Callback 接口。讀取響應時會阻塞當前線程。OkHttp 現階段不提供異步 api 來接收響應體。

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")
        .build();
    client.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Request request, Throwable throwable) {
            throwable.printStackTrace();
        }
        @Override public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }
            System.out.println(response.body().string());
        }
    });
}

訪問 Header:

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .addHeader("Accept", "application/vnd.github.v3+json")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println("Server: " + response.header("Server"));
    System.out.println("Date: " + response.header("Date"));
    System.out.println("Vary: " + response.headers("Vary"));
}

POST TO A SERVER

Posting a String:

public static final MediaType jsonReq = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(jsonReq, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

Posting Streaming:

public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }
        @Override public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers");
            sink.writeUtf8("-------");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s", i, factor(i)));
            }
        }
        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n) return factor(x) + "×" + i;
            }
            return Integer.toString(n);
        }
    };
    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(requestBody)
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

Posting a File:

public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    File file = new File("README.md");
    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

Posting from parameters:

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
        .add("search", "Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

Posting a multipart request:

private static final String IMGUR_CLIENT_ID = ...;
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    // 使用 imgur 圖片上傳 API,詳見 https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addPart(
            Headers.of("Content-Disposition", "form-data; name=\"title\""),
            RequestBody.create(null, "Square Logo"))
        .addPart(
            Headers.of("Content-Disposition", "form-data; name=\"image\""),
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();
    Request request = new Request.Builder()
        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
        .url("https://api.imgur.com/3/image")
        .post(requestBody)
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

Posting Json with Gson

private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();
public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/gists/c2a7c39532239ff261be")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
    for (Map.Entry entry : gist.files.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue().content);
    }
}
static class Gist {
    Map files;
}
static class GistFile {
    String content;
}

Response Caching

要緩存響應,你需要一個可讀寫的緩存目錄,以及緩存大小的限制。這個緩存目錄應該是私有的,不被信任的程序不應能讀取緩存內容。同一個緩存目錄同時被多個緩存實例訪問是錯誤的。大多數程序只需調用一次 new OkHttpClient(),在第一次調用時配置好緩存,其他地方複用這個實例即可,否則兩個緩存實例會互相干擾、破壞響應緩存,甚至可能導致崩潰。響應緩存使用 HTTP 頭作為配置:你可以在請求頭中添加 Cache-Control: max-stale=3600,OkHttp 緩存會支援;服務端则通过響應頭確定緩存時長,例如使用 Cache-Control: max-age=9600。

private final OkHttpClient client;
public CacheResponse(File cacheDirectory) throws Exception {
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(cacheDirectory, cacheSize);
    client = new OkHttpClient();
    client.setCache(cache);
}
public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")
        .build();
    Response response1 = client.newCall(request).execute();
    if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
    String response1Body = response1.body().string();
    System.out.println("Response 1 response: " + response1);
    System.out.println("Response 1 cache response: " + response1.cacheResponse());
    System.out.println("Response 1 network response: " + response1.networkResponse());
}

Canceling a Call

final Call call = client.newCall(request);
call.cancel();

Timeouts

private final OkHttpClient client;
public ConfigureTimeouts() throws Exception {
    client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
}

Handling Authentication

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
    client.setAuthenticator(new Authenticator() {
        @Override public Request authenticate(Proxy proxy, Response response) {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
        }
        @Override public Request authenticateProxy(Proxy proxy, Response response) {
            return null; // Null 表示不進行驗證
        }
    });
    Request request = new Request.Builder()
        .url("https://publicobject.com/secrets/hellosecret.txt")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

為避免驗證失敗時多次重試,我們可以返回 null 來放棄驗證:

if (responseCount(response) >= 3) {
    return null; // 失敗 3 次後放棄
}
// 添加以下方法
private int responseCount(Response response) {
    int result = 1;
    while ((response = response.priorResponse()) != null) {
        result++;
    }
    return result;
}

Interceptors

class LoggingInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        logger.info(String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        logger.info(String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }
}

Application Interceptors:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());

Network Interceptors

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new LoggingInterceptor());
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved