<源码系列> OkHttp3之一:用法介绍

开门见山,直奔主题~

目录

  • OkHttp3简介

  • OkHttp3用法
    1、GET请求
    ---- 同步
    ---- 异步
    ---- GET请求下载文件
    2、POST请求:
    ---- 提交String请求
    ---- 提交数据流请求
    ---- 提交文件请求
    ---- 提交表单请求
    ---- 提交multipart请求
    3、取消调用
    4、配置相关
    ---- 处理响应缓存
    ---- 处理响应超时
    ---- 处理单独配置请求参数
    ---- 处理身份验证
    5、拦截器

  • OkHttp3源码分析(待续)

  • OkHttp3封装应用(待续)

OkHttp3简介

1、链接:

官网:https://square.github.io/okhttp/
GitHub:https://github.com/square/okhttp

2、简介:

官方:An HTTP & HTTP/2 client for Android and Java applications

OKHttp是一个处理网络请求的开源项目,Android 当前最火热网络框架之一,由移动支付Square公司贡献,用于替代HttpUrlConnection和Apache HttpClient(Android6.0 API 23里已移除HttpClient)。

3、特征:

OkHttp是一个默认有效的HTTP客户端
· 支持http2,对一台机器的所有请求共享同一个socket。
· 连接池减少了请求延迟(如果HTTP/2 不可用)。
· 透明的GZIP压缩减少响应数据的大小。
· 缓存响应数据,避免了重复的网络请求。

~自动恢复一般的连接问题
~ 若你的服务器配有多个IP地址,请求失败时自动重试主机的其他IP,自动重定向
~ OkHttp使用现代TLS技术(SNI1.3,ALPN)初始化新的连接。
~OkHttp的API很友好,请求和响应采用建造者模式可进行链式调用
~支持阻塞式的同步调用,和回调式的异步调用。

注意:
OkHttp最新版本(3.14.0)支持Android 5.0+(API级别21+)和Java 8+。
如果考虑到版本限制的问题,可以使用低版本(3.12.0)
本文参考版本为3.12.0

OkHttp3用法

1、引入下载

//这里未使用最新的,是因为3.14.0版本需要在Android5.0+和Java8+版本以上
implementation("com.squareup.okhttp3:okhttp:3.12.0")

你也可能需要引入Okio(用于OkHttp,对于I/O操作和缓冲区大小都做了更好的处理):

//没用最新的2.xx.xx版本是因为Kotlin的原因
compile 'com.squareup.okio:okio:1.17.3'

若需要看最新版本,请移步官方GitHub地址,见上。

添加权限:

<uses-permission android:name="android.permission.INTERNET" />
//可能用到
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2、使用:

使用前先了解OkHttp核心的几个类:
· OkHttpClient:HTTP客户端对象,应当作为单例被共享。
· Request:访问请求类,对HTTP请求的相关参数的封装。
· RequestBody:请求体类,对HTTP请求体的封装,用于Post请求中。
· MediaType:请求的数据类型,指明请求数据的格式(json/image/file...)
· Response:响应结果类,即网络请求的响应结果。

· execute():同步的请求方法,会阻塞线程,需要在工作线程中调用。
· enqueue(Callback callBack):异步的请求方法,可直接调用。
··· 而Callback中的回调方法是执行在子线程中的,因此不能在其中进行UI更新操作。

2.1、GET请求

同步:

    /**
     * 同步Get请求
     * @param url 请求地址
     */
    private void callGetSynchronous(String url) {
        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
            .get()  //此处可以省略不写,默认就是Get请求
            .url(url)
            .build();
        //同步调用会阻塞主线程,因此需要在子线程进行
        //这里只是演示,实际开发中最好使用线程池等相关技术处理
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code " + response);
                    }
                    Log.e(TAG, "body==>" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

异步:

    /**
     * 异步GE请求
     * @param url 请求地址
     */
    private void callGetAsynchronous(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .get()
            .url(url)
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "onFailure::Thread==>" + Thread.currentThread().getName());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code " + response);
                }
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                Log.e(TAG, "onResponse::body==>" + response.body().string());
            }
        });

    }

GET请求下载文件:

    /**
     * 异步GET下载文件
     */
    private void callDownloadFile() {
        String fileUrl = "https://publicobject.com/helloworld.txt";
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
            .url(fileUrl)
            .get()
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull final Response response) throws IOException {
                //Thread[OkHttp https://publicobject.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                //保存文件,此处省略
                saveFile(response.body().byteStream());
            }
        });

    }

·说明:
1、同步Get请求中Response 的相关方法(至少body()方法)会阻塞线程,不能在主线程(UI线程)中进行调用,否则会报错:android.os.NetworkOnMainThreadException
2、从打印结果来看,异步Get请求的回调方法是在子线程(OkHttp自定义的线程名称)中的,所以不可以在回调方法中进行UI的更新。
3、在异步Get请求的回调方法中response.body().string()只能有效的调用一次,否则会报错:java.lang.IllegalStateException: closed

2.2、POST请求

POST请求在构造时,需要传入一个RequestBody对象,用它来携带我们要提交的数据。

一般有以下几种构造方式:
RequestBody.create()

备注:
官方测试数据:
url:https://api.github.com/markdown/raw
MediaType:text/x-markdown; charset=utf-8

提交String请求:

    /**
     * 异步POST请求字符串
     */
    private void callPostString() {
        String url = "https://api.github.com/markdown/raw";
        String postString = "This is POST RequestBody";
        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, postString);
        Request request = new Request.Builder()
            .post(body)
            .url(url)
            .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                Log.e(TAG, response.protocol()  //http协议
                    + "," + response.code() //响应码
                    + "," + response.message());    //响应状态
                Headers headers = response.headers();   //响应头
                for (int i = 0; i < headers.size(); i++) {
                    Log.e(TAG, headers.name(i) + ":" + headers.value(i));
                }
                Log.d(TAG, "onResponse::" + response.body().string());  //响应内容
            }
        });
    }

提交数据流请求:

    /**
     * 异步POST请求提交数据流
     */
    private void callPostStream() {
        String url = "https://api.github.com/markdown/raw";
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(@NonNull BufferedSink sink) throws IOException {
                sink.writeUtf8("POST STREAM REQUESTBODY");
            }
        };


        Request request = new Request.Builder()
            .post(requestBody)
            .url(url)
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                Log.e(TAG, response.protocol()  //http协议
                    + "," + response.code() //响应码
                    + "," + response.message());    //响应状态
                Headers headers = response.headers();   //响应头
                for (int i = 0; i < headers.size(); i++) {
                    Log.e(TAG, headers.name(i) + ":" + headers.value(i));
                }
                Log.d(TAG, "onResponse::" + response.body().string());  //响应内容
            }
        });
    }

提交文件请求:

    /**
     * 异步POST提交文件
     */
    private void callPostFile() {
        String url = "https://api.github.com/markdown/raw";
        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        File file = new File("POST_FILE.md");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_MARKDOWN, file);
        Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                Log.d(TAG, "onResponse::" + response.body().string());
            }
        });
    }

提交表单请求:
在提交表单请求时,需要使用RequestBody 的子类FormBody 来构造表单数据,namevalue 将使用HTML兼容的表单URL编码进行编码。
通过查看源码,其中namevalue 分别存储在如下的集合中:

  private final List<String> encodedNames;
  private final List<String> encodedValues;
    /**
     * 异步POST提交表单
     */
    private void callPostForm() {
        String url = "https://en.wikipedia.org/w/index.php";
        FormBody formBody = new FormBody.Builder()
            .add("formKey", "formValue")
            .add("search", "Jurassic Park")
            .build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                Log.d(TAG, "onResponse::" + response.body().string());
            }
        });
    }

提交multipart请求:
MultipartBody.Builder 可以构建与HTML文件上传表单兼容的复杂的请求体。multipart请求体中的每部分请求都是一个请求体,并可以自定义请求头。如果可用的话,这些请求头应当用来描述这一部分的请求,例如这部分的 Content-Disposition 。如果 Content-LengthContent-Type 可用的话,它们将会被自动添加到请求头中。(注:翻译自官方例子,如有错误,请指正。
multipart请求就是将多个请求体封装到一起,进行数据请求。

    /**
     * 异步POST提交multipart请求
     */
    private void callPostMultipart() {
        String IMGUR_CLIENT_ID = "..."; //请自定义id
        String url = "https://api.imgur.com/3/image";
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)    //multipart/form-data
            .addFormDataPart("title", "Square Logo")
            .addFormDataPart("image", "logo-square.png",
                RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url(url)
            .post(requestBody)
            .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure::" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //Thread[OkHttp https://api.github.com/...,5,main]
                Log.e(TAG, "onResponse::Thread==>" + Thread.currentThread());
                //isUIThread==>false
                Log.e(TAG, "isUIThread==>" + (Looper.getMainLooper().getThread()==Thread.currentThread()));
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                Log.d(TAG, "onResponse::" + response.body().string());
            }
        });
    }

·说明:
1、如果响应正文是超过1Mb的,要避免使用string() 方法,因为此方法将会把整个内容加载到内存中;作为替代方式,最好可以用stream来处理响应正文。

But if the response body is large (greater than 1 MiB), avoid string() because it will load the entire document into memory. In that case, prefer to process the body as a stream.

2.3、取消调用:

调用Call.cancel() 会立即停止正在进行的调用。如果某个线程当前正在写入或读取一个响应的话,它将会受到一个IOException 异常。比如说,当您的用户离开了应用的时候,是不在需要进行调用请求或响应的了,便可以用此方法来节省网络开销。同步和异步调用都可以取消。

    /**
     * 取消调用
     */
    private void callCancel() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url("http://httpbin.org/delay/2")
            .build();
        final long startNanos = System.nanoTime();
        final Call call = client.newCall(request);
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                //1.00 Canceling call.
                Log.e(TAG, String.format("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f));
                call.cancel();
                //1.01 Canceled call.
                Log.e(TAG, String.format("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f));
            }
        }, 1, TimeUnit.SECONDS);

        Log.e(TAG, String.format("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.e(TAG, String.format("%.2f Call was expected to fail, but completed: %s%n",
                        (System.nanoTime() - startNanos) / 1e9f, response));
                } catch (IOException e) {
                    //1.02 Call failed as expected: java.io.IOException: Canceled
                    Log.e(TAG, String.format("%.2f Call failed as expected: %s%n",
                        (System.nanoTime() - startNanos) / 1e9f, e));
                    e.printStackTrace();
                }
            }
        }).start();

    }

2.4、配置相关

处理响应缓存:
如果需要缓存响应结果,您需要一个可以读写的并限制缓存大小的缓存目录,此目录必须是私有的,不能被非信任的应用程序读取缓存内容。

让多个缓存同时访问同一缓存目录是错误的。大多数应用程序应该只调用一次new OkHttpClient() ,使用缓存配置它,并在任何地方使用同一实例。否则,两个缓存实例将相互影响,破坏响应缓存,并可能导致程序崩溃。

响应缓存使用HTTP请求头进行所有配置。您可以添加类似的请求标头如Cache-Control: max-stale=3600 ,OkHttp的缓存将依照它们设置。您的服务器配置使用自身的响应头缓存响应时间,例如Cache-Control: max-age=9600。这些缓存缓存的响应头可强制使用缓存数据,强制使用网络数据,或强制使用GET条件验证的网络数据。
要避免使用缓存,请使用CacheControl.FORCE_NETWORK,要避免使用网络数据,请使用CacheControl.FORCE_CACHE
·警告:如果您使用FORCE_CACHE 并且还要请求网络数据,OkHttp将返回504 Unsatisfiable Request 响应。

    /**
     * 响应缓存
     */
    private void callCache() {
        String url = "http://publicobject.com/helloworld.txt";
        File cacheDir = FileUtil.getExternalCacheDirectory(mContext, "cache_okhttp");
//        File cacheDir = new File(FileUtil."cache_okhttp");
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(cacheDir, cacheSize);
        final OkHttpClient client = new OkHttpClient.Builder()
            .cache(cache)
            .build();

        final Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String response1Body = null;
                try {
                    Response response1 = client.newCall(request).execute();
                    if (!response1.isSuccessful()) {
                        throw new IOException("Unexpected code " + response1);
                    }
                    response1Body = response1.body().string();
                    //Response 1 response:         Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
                    Log.e(TAG, "Response 1 response:          " + response1);
                    //Response 1 cache response:   null
                    Log.e(TAG, "Response 1 cache response:    " + response1.cacheResponse());
                    //Response 1 network response: Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
                    Log.e(TAG, "Response 1 network response:  " + response1.networkResponse());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String response2Body = null;
                try {
                    Response response2 = client.newCall(request).execute();
                    if (!response2.isSuccessful()) {
                        throw new IOException("Unexpected code " + response2);
                    }
                    response2Body = response2.body().string();
                    //Response 2 response:        Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
                    Log.e(TAG, "Response 2 response:          " + response2);
                    //Response 2 cache response:  Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
                    Log.e(TAG, "Response 2 cache response:    " + response2.cacheResponse());
                    //Response 2 network response: null
                    Log.e(TAG, "Response 2 network response:  " + response2.networkResponse());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Response 2 equals Response 1? true
                Log.e(TAG, "Response 2 equals Response 1? " + response1Body.equals(response2Body));

            }
        }).start();

    }

处理响应超时:
当连接不可用或失败时,可以通过超时来响应一个失败结果,网络连接断开可能是由于客户端的连接问题,服务器有效性的问题,或者其他问题导致的。OkHttp支持连接超时、读取超时和写入超时等。

    /**
     * 超时
     */
    private void callTimeouts() {
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
        Request request = new Request.Builder()
            .url("http://httpbin.org/delay/2")
            .get()
            .build();
        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    //Response completed: Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/delay/2}
                    Log.e(TAG, "Response completed: " + response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

处理单独配置请求参数:
全部的客户端配置都会在OkHttpClient 中生效,包括代理设置,超时,已经缓存等。当你需要修改单独请求的配置时,可以调用OkHttpClient.newBuilder() 。这将返回与原始客户端共享的相同连接池、调度器和配置的构造器中。

   /**
     * 个性化配置
     */
    private void callPercallConfiguration() {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
            .url("http://httpbin.org/delay/1")
            .get()
            .build();

        final OkHttpClient client1 = client.newBuilder()
            .readTimeout(500, TimeUnit.MILLISECONDS)
            .build();
        final OkHttpClient client2 = client.newBuilder()
            .readTimeout(3000, TimeUnit.MILLISECONDS)
            .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response1 = client1.newCall(request).execute();
                    Log.e(TAG, "Response 1 succeeded: " + response1);
                } catch (IOException e) {
                    //Response 1 failed: java.net.SocketTimeoutException: timeout
                    Log.e(TAG, "Response 1 failed: " + e);
                    e.printStackTrace();
                }

                try {
                    Response response2 = client2.newCall(request).execute();
                    //Response 2 succeeded: Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/delay/1}
                    Log.e(TAG, "Response 2 succeeded: " + response2);
                } catch (IOException e) {
                    Log.e(TAG, "Response 2 failed: " + e);
                    e.printStackTrace();
                }
                //readTime1==>500,,readTime2==>3000
                Log.e(TAG, "readTime1==>" + client1.readTimeoutMillis() + ",," +
                           "readTime2==>" + client2.readTimeoutMillis());
            }
        }).start();

    }

处理身份验证:
OkHttp可以自动重试未经身份验证的请求。当响应结果为401 Not Authorized 时,一个名为Authenticator 的类会要求提供凭据。实现应该构建一个包含丢失凭据的新请求。如果没有可用的凭据,则返回null以跳过重试。

使用Response.challenges() 会得到任意的身份验证挑战计划和领域。在完成Basic挑战时,使用Credentials.basic(username, password) 进行编码请求头。

    /**
     * 身份验证
     */
    private void callAuthenticate() {
        OkHttpClient client = new OkHttpClient.Builder()
            .authenticator(new Authenticator() {
                @Nullable
                @Override
                public Request authenticate(@Nullable Route route, @NonNull Response response) throws IOException {
                    if (response.request().header("Authorization") != null) {
                        return null; // 放弃验证,已经得到了一个身份验证
                    }
                    //Authenticating for response: Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://publicobject.com/secrets/hellosecret.txt}
                    Log.e(TAG, "Authenticating for response: " + response);
                    //Challenges: [Basic authParams={realm=OkHttp Secrets}]
                    Log.e(TAG, "Challenges: " + response.challenges());
                    String credential = Credentials.basic("jesse", "password1");
                    return response.request().newBuilder()
                        .header("Authorization", credential)
                        .build();
                }
            })
            .build();

        Request request = new Request.Builder()
            .url("http://publicobject.com/secrets/hellosecret.txt")
            .get()
            .build();
        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code " + response);
                    }
                    //Response:: 此处省略好多字......
                    Log.e(TAG, "Response::" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

您可以通过以下两种方式在身份验证不起作用时来跳过重试请求:

  • 当已经有验证身份的时候:
  if (credential.equals(response.request().header("Authorization"))) {
    return null; // If we already failed with these credentials, don't retry.
   }

  • 当达到程序限制的时候:
  if (responseCount(response) >= 3) {
    return null; // If we've failed 3 times, give up.
  }

以上代码依赖于此responseCount() 方法:

  private int responseCount(Response response) {
    int result = 1;
    while ((response = response.priorResponse()) != null) {
      result++;
    }
    return result;
  }
2.5、拦截器(interceptor)

拦截器是一种强大的机制,可以进行监视,重写和重试调用。

使用拦截器,要实现Interceptor 接口,并实现其中的方法intercept(Interceptor.Chain chain) ,在实现此方法中,调用chain.proceed(request) 是每个拦截器实现的关键部分。因为它是所有HTTP执行的地方,并产生满足请求的响应结果。

您可以同时加入多个拦截器,拦截器会链接在一起,因为OkHttp会用一个列表进行跟踪每一个拦截器,并按顺序调用拦截器。下图是拦截器的示意图:


Interceptor拦截器示意图

从示意图中可以看出,拦截器有两种:Application InterceptorsNetwork Interceptors

示例:

  • 日志拦截器
    /**
     * 日志拦截器
     */
    class LoggingInterceptor implements Interceptor {
        @NonNull
        @Override
        public Response intercept(@NonNull Interceptor.Chain chain) throws IOException {
            Request request = chain.request();

            long t1 = System.nanoTime();
            Log.e(TAG, String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();
            Log.e(TAG, String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));

            return response;
        }
    }

  • 注册Application Interceptors
    /**
     * Application Interceptors
     */
    private void callApplicationInterceptors() {
        final OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new LoggingInterceptor())
            .build();

        final Request request = new Request.Builder()
            .url("http://www.publicobject.com/helloworld.txt")
            .header("User-Agent", "OkHttp Example")
            .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    response.body().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    /*
     打印结果:(一次)
     (打印的是:request.url())
     Sending request http://www.publicobject.com/helloworld.txt on null
     User-Agent: OkHttp Example

     (打印的是:response.request().url())
     Received response for https://publicobject.com/helloworld.txt in 4683.0ms
     Server: nginx/1.10.0 (Ubuntu)
     Date: Mon, 25 Mar 2019 14:34:52 GMT
     Content-Type: text/plain
     Content-Length: 1759
     Last-Modified: Tue, 27 May 2014 02:35:47 GMT
     Connection: keep-alive
     ETag: "5383fa03-6df"
     Accept-Ranges: bytes
     */
  • 注册Network Interceptors
    /**
     * Network Interceptors
     */
    private void callNetInterceptors() {
        final OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(new LoggingInterceptor())
            .build();

        final Request request = new Request.Builder()
            .url("http://www.publicobject.com/helloworld.txt")
            .header("User-Agent", "OkHttp Example")
            .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = client.newCall(request).execute();
                    response.body().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    /*
     打印结果:
          (第一次)
     (初始化请求)
         Sending request http://www.publicobject.com/helloworld.txt on Connection{www.publicobject.com:80, proxy=DIRECT hostAddress=www.publicobject.com/54.187.32.157:80 cipherSuite=none protocol=http/1.1}
         User-Agent: OkHttp Example
         Host: www.publicobject.com
         Connection: Keep-Alive
         Accept-Encoding: gzip

         Received response for http://www.publicobject.com/helloworld.txt in 398.1ms
         Server: nginx/1.10.0 (Ubuntu)
         Date: Mon, 25 Mar 2019 14:41:14 GMT
         Content-Type: text/html
         Content-Length: 194
         Connection: keep-alive
         Location: https://publicobject.com/helloworld.txt

          (第二次)
     (重定向)
         Sending request https://publicobject.com/helloworld.txt on Connection{publicobject.com:443, proxy=DIRECT hostAddress=publicobject.com/54.187.32.157:443 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 protocol=http/1.1}
         User-Agent: OkHttp Example
         Host: publicobject.com
         Connection: Keep-Alive
         Accept-Encoding: gzip
    
         Received response for https://publicobject.com/helloworld.txt in 1498.7ms
         Server: nginx/1.10.0 (Ubuntu)
         Date: Mon, 25 Mar 2019 14:41:16 GMT
         Content-Type: text/plain
         Content-Length: 1759
         Last-Modified: Tue, 27 May 2014 02:35:47 GMT
         Connection: keep-alive
         ETag: "5383fa03-6df"
         Accept-Ranges: bytes 
     */

从上面的示例来比较两者区别:

  • 注册的调用方式不同:
    //Application Interceptors
    OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(自定义的应用拦截器);
    //Network Interceptors
    OkHttpClient client = new OkHttpClient.Builder()
        .addNetworkInterceptor(自定义的网络拦截器);
  • 调用次数不同:
    Application Interceptors 调用了一次,在返回响应内容时调用了一次
    Network Interceptors 调用了两次,一次在初始请求时,一次用于重定向
  • 网络请求还包含更多数据,例如通过OkHttp添加的请求头Accept-Encoding: gzip ,用于告知对响应压缩的支持。网络拦截器Chain 具有非空值Connection ,可用于询问用于连接到Web服务器的IP地址和TLS配置。

每种拦截器的有点:

应用拦截器

  • 不需要担心重定向和重试等中间响应。
  • 即使从缓存提供HTTP响应,也始终调用一次。
  • 观察应用程序的原始意图。没有关注OkHttp注入的请求头If-None-Match
  • 允许绕过且不调用Chain.proceed()
  • 允许重试并进行多次调用Chain.proceed()

网络拦截器

  • 能够对重定向和重试等中间响应进行操作。
  • 不调用网络而使用缓存响应。
  • 观察数据,就像它将通过网络传输一样。
  • 访问Connection请求。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335

推荐阅读更多精彩内容