欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OkHttp的基本使用-3(添加拦截器和GET请求的参数拼接)

程序员文章站 2022-06-05 18:46:07
...

在上一篇,讲解了Http基本的GET和POST请求,如果不了解可以参考我的上一篇文章 OkHttp的基本使用-2(使用最简单的方式)

OkHttp的拦截器有两种,一种为网络拦截器,别外一种为应用拦截器,下面是采用网络拦截器进行下载

上一篇讲了一个文件下载的例子,但是在真实的项目中,使用上面所讲的方法,代码很多,而且难以维护,下面进行使用拦截器下载文件的方式进行进度监听

先实现一个ResponseBody

package com.app.rui.okhttpdemo;

import android.support.annotation.Nullable;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

public class ProgressResponseBody extends ResponseBody {
    private ResponseBody mResponseBody;
    private Source mBufferedSource;
    private OnProgressListener mListener;

    public ProgressResponseBody(ResponseBody responseBody, OnProgressListener listener) {
        mResponseBody = responseBody;
        mListener = listener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mResponseBody.contentType();
    }

    @Override
    public long contentLength() {
        return mResponseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if(mBufferedSource == null){
            mBufferedSource = getSource(mResponseBody.source());
        }
        return Okio.buffer(mBufferedSource);
    }

    private Source getSource(Source source){
        return new ForwardingSource(source) {
            private long mContentSize;
            private long mSum;
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                if(mContentSize == 0){
                    mContentSize = contentLength();
                }
                long len = super.read(sink, byteCount);
                mSum += len == -1 ? 0 : len;
                int progress = (int) ((mSum * 1.0f / mContentSize) *100);
                if(mListener != null){
                    mListener.changeListener(progress);
                    if(mSum == mContentSize){
                        mListener.downloadFinish();
                    }
                }
                return len;
            }
        };
    }
}
监听进度的回调

package com.app.rui.okhttpdemo;

public interface OnProgressListener {
    void downloadFinish();
    void changeListener(int progress);
}
接下来将Response添加到网络监听器中

OkHttpClient client = new OkHttpClient
        .Builder()
        .addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                return response.newBuilder().body(new ProgressResponseBody(response.body(), new OnProgressListener() {
                    @Override
                    public void downloadFinish() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void changeListener(final int progress) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProgressBar.setProgress(progress);
                            }
                        });
                    }
                })).build();
            }
        })
        .build();
Request request = new Request.Builder()
        .url("http://192.168.0.103/1.wmv")
        .get()
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d("TAG12", e.getLocalizedMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d("TAG12", response.message());
        if (response.isSuccessful()) {
            //Log.d("TAG12", response.body().string());
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(path, "1.wmv");
            OutputStream os = new FileOutputStream(file);
            InputStream is = response.body().byteStream();
            int len = -1;
            byte[] b = new byte[1024];
            while (-1 != (len = is.read(b))){
                os.write(b, 0, len);
                Log.d("TAG12", "正在下载");
            }

            Log.d("TAG12", "下载完成");
        }
    }
});

其实添加上传文件的进度监听一样的,还可以在下载文件也放到一个监听等等

HttpUrl是可以进行拼接参数的

相关标签: 网络 应用