OkHttp协议介绍以及文件下载和上传+OkHttp协议封装+OkHttp拦截器

OkHttp协议

okhttp是一个第三方类库,用于android中请求网络
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary)

文件下载用Get方式

 OkHttpClient okHttpClient = new OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder().url(u)
                .get()
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();

                long length = body.contentLength();
                Message message = Message.obtain();
                message.what = Model.DownLoad_Max;
                message.obj = (int)length;
                handler.sendMessage(message);

                InputStream inputStream = body.byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                byte[] bytes = new byte[1024];
                int len = 0;
                int count = 0;
                while ((len=inputStream.read(bytes))!=-1) {
                    count+=len;
                    fileOutputStream.write(bytes,0,len);
                    Message message1 = Message.obtain();
                    message1.what = Model.DownLoad_Progress;
                    message1.obj = count;
                    handler.sendMessage(message1);
                }

            }
        });

文件上传用Post方式

OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .build();

        MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file",filename, RequestBody.create(MediaType.parse("image/jpg"),new File(path)))
                .build();

        Request request = new Request.Builder().url(u)
                .post(multipartBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handler.sendEmptyMessage(Model.UpLoad_Finish);
            }
        });

OkHttp协议封装

将OkHttp封装成工具类并写上传和下载方法,代码如下:

public static OkHttpClient okHttpClient;
    private static OkHttpUtils okHttpUtils = new OkHttpUtils();
    private OkHttpUtils(){}
    public static OkHttpUtils getOkHttpUtils(){
        okHttpClient = new OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .build();
        return okHttpUtils;
    }

   

    public void get(String url, final CallBack callBack){
        Request request = new Request.Builder().get()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callBack.onSuccess(response);
            }
        });
    }

    public void post(String url, HashMap<String,String> map, final CallBack callBack){
        Set<Map.Entry<String, String>> entries = map.entrySet();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entrie : entries) {
            String key = entrie.getKey();
            String value = entrie.getValue();
            builder.add(key,value);
        }
        FormBody formBody = builder.build();

        Request request = new Request.Builder().post(formBody)
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callBack.onSuccess(response);
            }
        });
    }

OkHttp拦截器

主要用于拦截发送信息

public static OkHttpClient okHttpClient;
    private static OkHttpUtils okHttpUtils = new OkHttpUtils();
    private OkHttpUtils(){}
    public static OkHttpUtils getOkHttpUtils(){
        okHttpClient = new OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(interceptor)
                .build();
        return okHttpUtils;
    }

static HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.d("###",message);
        }
    });

    static Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder().header("token", "token").build();
            return chain.proceed(request);
        }
    };

你可能感兴趣的:(第二个月)