OKHttp协议+封装

原则:

代码复用性+只有一个client对象。(单例模式)、
介绍:
okhttp是第三方类库,用于请求网络。

三个坑:

token拦截log拦截之前。
response 只能调用一次。
获得请求数据总长度,有时候返回-1,需要设置请求头:“Accept-Encoding”,"identity

拦截器

log拦截器
打印整个请求过程,方便调试代码。
在这里插入图片描述
token拦截器
必须在log拦截器之前
在request内添加请求头,

在这里插入图片描述在这里插入图片描述

代码

单例模式

 	//单例模式 - 只会创建一个clicent
    private OkHttpClient client;

    private OkHttpUtils() {

        //log拦截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
        //显示整个Http请求
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor interceptor = new Interceptor(){

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


        Log.i("TAG", "创建OkHttpUtils ");
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                //添加token拦截器 -- 必须在log拦截器之前
                .addInterceptor(interceptor)
                //添加log拦截器 -- OkHttp查找
                .addInterceptor(httpLoggingInterceptor);


         client = builder.build();
    }

    //自行实例化 - 懒汉式
    private static OkHttpUtils okHttpUtils=null;

    //公开方法
    public static OkHttpUtils getInstance(){
        if (okHttpUtils==null) {
            synchronized (StringBuilder.class){
                if (okHttpUtils==null) {
                    okHttpUtils=new OkHttpUtils();

                }
            }
        }
        return okHttpUtils;
    }

get请求数据

 //get请求
    public void doget(String url, final Listener listener){

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

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            //失败
                listener.Error(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            //成功
                listener.Success(response.body().string());

            }
        });

    }

post请求数据

 //post请求
    public void dopost(String url,Map<String,String> maps, final Listener listener ){
        Request.Builder builder = new Request.Builder();
        builder.url(url);

        // limit=20&page=1
        FormBody.Builder builder1 = new FormBody.Builder();

        Set<Map.Entry<String, String>> entries = maps.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();

            builder1.add(key,value);
        }


        FormBody build = builder1.build();

        builder.post(build);
        Request request = builder.build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.Error(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.Success(response.body().string());
            }
        });

    }

get下载

 //get下载
    public void doget(String url, final String path, final Listener listener){

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        builder.get();

        //请求头  Connection: Keep-Alive
//        builder.header("","");

        Request request = builder.build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.Error(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                long l = body.contentLength();//获得总大小
                listener.setMax((int) l);

                InputStream is = body.byteStream();//响应体 -- > 输入流
                //边读边写
                int len=0;
                int count=0;
                byte[] bys = new byte[1024];
                FileOutputStream fos = new FileOutputStream(path);
                while ((len=is.read(bys))!=-1) {
                    fos.write(bys,0,len);
                    count+=len;
                    listener.setProgress(count);

                    if (count==l) {
                        listener.finish();
                    }
                }
            }
        });

    }

上传文件

 //上传文件
    public void upload(String url, String path, String type, String filename, final Listener listener){
        //上传文件请求体
        MultipartBody build = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//设置方法
                .addFormDataPart("file", filename,//服务器端的名字
                        RequestBody.create(MediaType.parse(type),
                                new File(path)//sd卡路径
                        )).build();


        Request request = new Request.Builder()
                .url(url)
                .post(build)
                .build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.Error(e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.finish();

            }
        });

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值