okhttp的使用介紹

轉載請以鏈接形式標明出處:
本文出自:103style的博客


目錄

  • 簡介
  • 分支介紹
  • 使用示例
  • 混淆配置

簡介

okhttp 的優勢:

  • 採用連接池技術減少
  • 默認使用 GZIP 數據壓縮格式,降低傳輸內容的大小
  • 採用緩存避免重複的網絡請求
  • 支持 SPDYHTTP/2.0,對於同一主機的請求可共享同一 socket 連接
  • SPDYHTTP/2.0 不可用,還會採用連接池提高連接效率
  • 網絡出現問題、會自動重連(嘗試連接同一主機的多個ip地址)
  • 使用 okio 庫簡化數據的訪問和存儲

分支介紹

目前 okhttp 主要有三個分支:

  • 4.2.0:要求 Android 5.0+ (API level 21+) and on Java 8+
    • 源碼是用kotlin寫的。
    • 支持 TLS 1.3
    implementation("com.squareup.okhttp3:okhttp:4.2.0")
    
  • 3.14.2:要求 Android 5.0+ (API level 21+) and on Java 8+
    • 功能同 4.2.0 版本,區別是源碼是用java寫的。
    implementation("com.squareup.okhttp3:okhttp:3.14.2")
    
  • 3.12.0Android 2.3+ (API level 9+) and Java 7+.
    • 源碼是用java寫的。
    • 不支持 TLS 1.2 ,計劃在 2020年12月31日 前提供關鍵修復。
    implementation("com.squareup.okhttp3:okhttp:3.12.0")
    

使用示例

初始化 OkHttpClientThreadPoolExecutor

private OkHttpClient client = new OkHttpClient.Builder()
        .build();

private ThreadPoolExecutor service = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
        60L, TimeUnit.SECONDS,
        new SynchronousQueue<>(),
        r -> {
            Thread thread = new Thread(r);
            thread.setName(MainActivity.this.getPackageName());
            return thread;
        });
  • 同步請求示例

    private void runSync() {
        service.execute(() -> {
            try {
                Request request = new Request.Builder()
                        .url("https://publicobject.com/helloworld.txt")
                        .build();
    
                try (Response response = client.newCall(request).execute()) {
                    if (response.body() == null) {
                        return;
                    }
                    InputStream is = response.body().source().inputStream();
                    int r;
                    while ((r = is.read()) != -1) {
                        System.out.print((char) r);
                    }
                    System.out.println();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    
  • 異步請求示例

    private void runAsync() {
        Request request = new Request.Builder()
                .url("https://publicobject.com/helloworld.txt")
                .build();
    
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() == null) {
                    System.out.println("response.body() is null");
                    return;
                }
                InputStream is = response.body().source().inputStream();
                int r;
                while ((r = is.read()) != -1) {
                    System.out.print((char) r);
                }
                System.out.println();
            }
        });
    }
    
  • post請求示例

    private void post(String url, String json) throws Exception {
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
    
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.body() != null) {
            System.out.println(response.body().string());
        }
    }
    
  • 取消請求示例

    ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(1,
            r -> {
                Thread thread = new Thread(r);
                thread.setName(MainActivity.this.getPackageName());
                return thread;
            });
    
    public void run() {
        Request request = new Request.Builder()
                .url("http://httpbin.org/delay/2")
                .build();
    
        final long startNanos = System.nanoTime();
        final Call call = client.newCall(request);
    
        // Schedule a job to cancel the call in 1 second.
        service.schedule(() -> {
            System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
            call.cancel();
            System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
        }, 1, TimeUnit.SECONDS);
    
        System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
        service.execute(() -> {
            try (Response response = call.execute()) {
                System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
                        (System.nanoTime() - startNanos) / 1e9f, response);
            } catch (IOException e) {
                System.out.printf("%.2f Call failed as expected: %s%n",
                        (System.nanoTime() - startNanos) / 1e9f, e);
            }
        });
    
    }
    
  • 其他使用方式


混淆配置

# JSR 305 annotations are for embedding nullability information.
-dontwarn javax.annotation.**

# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase

# Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
# okio
-dontwarn org.codehaus.mojo.animal_sniffer.*

# OkHttp platform used only on JVM and when Conscrypt dependency is available.
-dontwarn okhttp3.internal.platform.ConscryptPlatform

以上

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章