okhttp封装

网络访问,是我们在实际开发中必不可少要用到的东西。现在也有很多网络框架可以够我们使用,本篇我们就以Okhttp进行访问网络把!如果对okhttp还不了解的童鞋可以去百度一下,下面我们开始对其进行封装。

//首先我们需要进行配置

compile 'com.squareup.okhttp3:okhttp:3.5.0'

接下来我们开始封装

//我们创建一个OKHttpManager类
public class OKHttpManager{
    //拿到OKHttpClient对象 
    private OKHttpClient client;
    private volatile static OKHttpManager manager;
    private Handler handler;

    //私有化构造方法
    private OKHttpManager(){
        client=new OKHttpClient();
        handler=new Handler(Looper.getMainLooper());
    }
    /**
    提供方法供外界调用
    */
    public static OKHttpManager getInstance(){
        OKHttpManager instance=null;
        synchronized(OKHttpManager.class){
            if(instance==null){
                manager=new OKHttpManager();
                instance=manager;
            }
        }
        return instance;
    }

/**
请求返回json的结果是一个字符串类型
*/
private void onSuccessJsonStringMethod(final String jsonvalue,final Func1 callBack){
    handler.post(new Runnable(){
        @override
        public void run(){
            if(callBack!=null){
                try{
                      callBack.onResponse(jsonValue);
                  }catch (Exception e){
                      e.printStackTrace();
                }
            }   
        }
    });
}

/**
请求返回json的结果是一个byte数组
*/
private void onSuccessJsonByteMethod(final byte [] result,final Func2 callBack){
    handler.post(new Runnable(){
    @override
    public void run(){
        if(callBack!=null){
            try{
            callBack.onResponse(result);
            }catch(Exception e){
                e.printStackTrace();
                }
            }
        }
    });
}

/**
请求返回json的结果是一个Image
*/
private void onSuccessImageMethod(final Bitmap bitmap,final Func3 callBack){
    handler.post(new Runnable(){
        @override
        public void run(){
            if(callBack!=null){
                try{
                    callBack.onResponse(bitmap);
                }catch(Execption e){
                        e.printStackTrace();
                }
            }
        }
    });
}

/**
若返回的是字符串类型就调用该方法
*/
public void asyncJsonStringMethod(final String url,Func1 callBack){
    final Request request=new Request.Builder().url(url).build();
    client.newCall(request).enquene(new CallBack{
        @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response!=null&&response.isSuccessful()){
                    onSuccessJsonStringMethod(response.body().string(),callBack);
              }
          }
    });
}

/**
若返回的是byte类型就调用该方法
*/
public void asyncJsonByteMethod(final String url,final Func2 callBack){
    final Request request=new Request.Builder().url(url).build();
    client.newCall(request).enquene(new CallBack{
        @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response!=null&&response.isSuccessful()){
                    onSuccessJsonStringMethod(response.body().bytes(),callBack);
              }
          }
    });
}

/**
若返回的是Image类型就调用该方法
*/
public void asyncJsonImageMethod(final String url,final Func3 callBack){
    final Request request=new Request.Builder().url(url).build();
    client.newCall(request).enquene(new CallBack{
        @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response!=null&&response.isSuccessful()){
                    byte [] result=response.body().bytes();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(result,0,result.length);
                    onSuccessImageMethod(bitmap,callBack);
              }
          }
    });
}



//创建回调接口
interface Func1{
    void onResponse(String result);
}

interface Func2{
    void onResponse(byte [] result);
}

interface Func3{
    void onResponse(Bitmap bitmap);
}

}
通过以上的封装,我们以后在项目中就可以直接去调用我们封装好的方法就OK了,就要就不会出现很多重复的代码,也提高了我们的开发效率。但是还有别以为okhttp就这点能耐,下面我们来对文件下载进行封装,我们都知道下载文件相对于下载图片或者只是获取网页的H5要大的多,当然okhttp也想到了开发者需要对大文件进行下载。

//顺便我们这里给我们的下载添加一个进度吧!

首先我们需要申请一个回调接口

interface Func4{
    void onResponse(int progress);
}

 /**
     * 异步处理
     * @param progress
     * @param callBack
     */
    private void onSuccessDownloadFileMethod(final int progress, final Func4 callBack){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(callBack!=null){
                    callBack.onResponse(progress);
                }
            }
        });
    }

/**
下载文件调用方法
*/
public void asyncFiledownloadURL(final String url, final Func4 callBack){
        final Request request= new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response!=null&&response.isSuccessful()){
                    InputStream is=null;
                    byte [] buf=new byte[1024*2];
                    int len=0;
                    FileOutputStream fos=null;
                    String SDPath= Environment.getExternalStorageDirectory().getAbsolutePath();
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        File file = new File(SDPath, "test1");
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            onSuccessDownloadFileMethod(progress,callBack);
                        }
                        fos.flush();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if(fos!=null){
                            fos.close();
                        }
                        if(is!=null){
                            is.close();
                        }
                    }
                }
            }
        });
    }
OK,大功告成,这样我们在下载文件的时候就很方便啦,不用再去重复写IO流那部分繁琐的代码。

好了,我们对okhttp的封装就暂且写在这吧,当然Okhttp的强大远远不止这点,希望感兴趣的童鞋能够好好的去研究研究okhttp。
最后,要感谢老罗大牛的博客,还要感谢一位忘了叫啥名的博主了0.0。这是本人的第一篇博客(android菜鸟一枚),虽然大多借鉴别人的作品,但是也有自己的一点点心血啦!希望这篇博能帮助到大家。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值