okhttp实战使用详解

我是把okhttp封装起来了,然后调用了,下面我直接把代码粘贴出来,直接用就可以了。
首先我把这个封装的东西放在一个单独的包里。
这里写图片描述
再看看里面写的都是什么吧

/**
 * Created by yzx on 2017/7/1
 */
public class CancelAble {

    Call call;

    public void cancel(){
        if(call != null){
            call.cancel();
            call = null;
        }
    }

}
/**
 *  封装的okhttp 2017/7/1
 */
public class OKClient {

    private final OkHttpClient client;
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final ArrayList<WeakReference<CancelAble>> callList = new ArrayList<>(0);

    public OKClient(OkHttpClient client){
        this.client = client;
    }


    /*=================== method======================*/


    public CancelAble get(String url , RequestParam params , OKRequestCallback callback){
        cleanCancelAbleList();

        String queryString = params == null?"":params.getQueryString();
        Request request = new Request.Builder().url(url+queryString).get().build();

        CancelAble cancelAble = new CancelAble();
        cancelAble.call = client.newCall(request);
        callList.add(new WeakReference<>(cancelAble));

        execCallback(cancelAble.call,callback);
        return cancelAble;
    }


    public CancelAble post(String url,RequestParam params , OKRequestCallback callback){
        cleanCancelAbleList();

        Request request = (params != null && params.hasFile()) ? getFilePostRequest(url,params) : getStringPostRequest(url,params);

        CancelAble cancelAble = new CancelAble();
        cancelAble.call = client.newCall(request);
        callList.add(new WeakReference<>(cancelAble));

        execCallback(cancelAble.call , callback);
        return cancelAble;
    }


    public CancelAble download(String url ,final File targetFile , boolean goon,final OKDownLoadCallback callback){
        cleanCancelAbleList();

        String rangeHeaderValue = null;
        if(goon && Util.isFileUseful(targetFile)){
            rangeHeaderValue = "bytes="+targetFile.length()+"-";
        } else {
            targetFile.delete();
            goon = false;
        }

        final long hasDownLen = goon ? targetFile.length() : 0;

        Request.Builder builder = new Request.Builder().url(url).get();
        if(goon) builder.addHeader("Range", rangeHeaderValue);

        CancelAble cancelAble = new CancelAble();
        cancelAble.call = client.newCall(builder.build());
        callList.add(new WeakReference<>(cancelAble));

        cancelAble.call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                if(call.isCanceled()) return ;
                if(response.isSuccessful()){
                    long total;
                    try{ total = Long.parseLong(response.header("Content-Length")); }
                    catch (Exception e){ total = 0; }
                    BufferedInputStream in = new BufferedInputStream(response.body().byteStream());
                    byte[] buffer = new byte[1024*8];
                    long hasWriteLen = hasDownLen;
                    int len;
                    RandomAccessFile out = new RandomAccessFile(targetFile, "rwd");
                    out.skipBytes((int)hasWriteLen);
                    long lastPublishTime = System.currentTimeMillis() - 334;
                    while((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                        hasWriteLen += len;
                        long now;
                        if((now = System.currentTimeMillis()) - lastPublishTime > 333){
                            publishProgress(callback,total,hasWriteLen);
                            lastPublishTime = now;
                        }
                    }
                    publishProgress(callback,total,total);
                    in.close();
                    out.close();
                    mHandler.post(new Runnable() {
                        public void run() {
                            callback.onComplete(targetFile);
                        }
                    });
                }else
                    mHandler.post(new Runnable() {
                        public void run() {
                            callback.onError(OKDownLoadCallback.ERROR_NET);
                        }
                    });
            }
            public void onFailure(Call call, IOException e) {
                if(call.isCanceled()) return ;
                mHandler.post(new Runnable() {
                    public void run() {
                        callback.onError(OKDownLoadCallback.ERROR_SDCARD);
                    }
                });
            }
        });

        return cancelAble;
    }


    public void cancelAll(){
        for (WeakReference<CancelAble> item : callList)
            if(item.get()!=null)
                item.get().cancel();
        callList.clear();
    }


    /*=================== internal======================*/


    private void publishProgress(final OKDownLoadCallback callback, final long total , final long current){
            mHandler.post(new Runnable() {
                public void run() {
                    try{
                        int p = (int)(1000 * current / total);
                        callback.onProgress(p >1000 ? 1000 : (p <0 ? 0 : p));
                    } catch(Exception e){ callback.onProgress(1000); }
                }
            });
    }


    private void cleanCancelAbleList(){
        if(callList.size() <= client.dispatcher().getMaxRequests())
            return ;
        ArrayList<WeakReference> readyRemoveList = new ArrayList<>(callList.size());
        for (WeakReference<CancelAble> item : callList)
            if(item.get() == null)
                readyRemoveList.add(item);
        callList.removeAll(readyRemoveList);
    }


    private Request getFilePostRequest(String url,RequestParam params){
        final MultipartBody.Builder builder = new MultipartBody.Builder("ook------------------------------------------ook").setType(MultipartBody.FORM);
        params.iteratorString(new RequestParam.KeyValueIteratorListener() {
            public void onIterator(String key, String value) {
              builder.addFormDataPart(key,value);
            }
        });
        params.iteratorFile(new RequestParam.KeyFileIteratorListener() {
            public void onIterator(String key, File file) {
               builder.addFormDataPart(key,file.getName(),
                       RequestBody.create(MediaType.parse("application/octet-stream") , file));
            }
        });
        return new Request.Builder().url(url).post(builder.build()).build();
    }


    private Request getStringPostRequest(String url,RequestParam params){
        final FormBody.Builder builder = new FormBody.Builder();
        if(params != null)
            params.iteratorString(new RequestParam.KeyValueIteratorListener() {
                public void onIterator(String key, String value) {
                    builder.add(key,value);
                }
            });
        return new Request.Builder().url(url).post(builder.build()).build();
    }


    private void execCallback(Call call,final OKRequestCallback callback){
        call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                if(callback == null) return ;
                if(call.isCanceled())  return ;
                final boolean isSuccess = response.isSuccessful();
                final String bodyString = response.body().string();
                final int code = response.code();
                mHandler.post(new Runnable() {
                    public void run() {
                        if(isSuccess){
                            try {
                                callback.onSuccess(bodyString);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        else  callback.onFailure(code);
                    }
                });
            }
            public void onFailure(Call call, IOException e) {
                if(callback == null) return ;
                if(call.isCanceled()) return ;
                mHandler.post(new Runnable() {
                    public void run() {
                        callback.onFailure(0);
                    }
                });
            }
        });
    }
}
/**
 * Created by yzx on 2016/9/1
 */
public interface OKDownLoadCallback {

     int ERROR_SDCARD = 1;
     int ERROR_NET = 2;


    void onComplete(File file);

    void onError(int errCode);

    void onProgress(int current); //0 - 1000

}
package com.example.xu.hyoa.httputil;

import org.json.JSONException;

/**
 * Created by yzx on 2017/7/1
 */
public interface OKRequestCallback {

    void onSuccess(String data) throws JSONException;

    void onFailure(int httpCode);

}
/**
 * Created by yzx on 2017/7/1
 */
public class RequestParam {

    private final HashMap<String,List<String>> stringMap = new HashMap<>(0);
    private final ArrayList<FileWrapper> fileList = new ArrayList<>(0);
    /**
     *添加string参数,key可以重复,重复则按照array参数处理
     */
    public void add(String key,String value){
        List<String> pv = stringMap.get(key);
        if(pv == null)
            stringMap.put(key, pv = new ArrayList<>(1));
        pv.add(value);
    }
    /**
     * 添加文件参数
     */
    public void addFile(String key , File file){
        if(Util.isFileUseful(file))
            fileList.add(new FileWrapper(file,key));
    }


    /* ==========================internal========================== */


    /* internal */
    String getQueryString(){
        if(stringMap.isEmpty())
            return "";

        final StringBuilder sb = new StringBuilder("?");
        iteratorString(new KeyValueIteratorListener() {
            public void onIterator(String key, String value) {
                sb.append(key).append("=").append(value).append("&");
            }
        });

        if(sb.length() == 1) sb.deleteCharAt(0);
        else sb.deleteCharAt(sb.length()-1);

        return sb.toString();
    }


    /* is upload file */
    boolean hasFile(){
        return !fileList.isEmpty();
    }


    /* iterate string params */
    void iteratorString(KeyValueIteratorListener iteratorListener){
        if(iteratorListener != null && !stringMap.isEmpty())
            for (Map.Entry<String, List<String>> entry : stringMap.entrySet())
                for (String item : ((entry.getValue() != null) ?entry.getValue() : new ArrayList<String>(0)))
                    iteratorListener.onIterator(entry.getKey() , item);
    }

    /* iterator file params */
    void iteratorFile(KeyFileIteratorListener iteratorListener){
        if(iteratorListener == null || fileList.isEmpty())
            return;
        for (FileWrapper item : fileList)
            iteratorListener.onIterator(item.key,item.file);
    }


    /* ============================class============================ */


    interface KeyFileIteratorListener{
        void onIterator(String key, File file);
    }

    interface KeyValueIteratorListener{
        void onIterator(String key, String value);
    }

    class FileWrapper{
        public FileWrapper(File file,String key){this.file=file;this.key=key;}
        File file;
        String key;
    }

}
/**
 * Created by yzx on 2017/7/71
 */
 class Util {

    static boolean isFileUseful(File file){
            return file != null && file.exists() && file.canRead() && !file.isDirectory();
    }

}

到这里封装的okhttp就完事了,然后使用方法

在那个类里用 需要先声明
声明一下,把下面复制就好了。

private OKClient client = new OKClient(new OkHttpClient());

get 请求

 /* get 请求 */
 //url   *****这是请求接口
    public void get(View view){
        RequestParam param = new RequestParam();
        param.add("fuck","fuck1");
        param.add("fuck","fuck2");//这是参数
        /* 这个CancelAble对象, 可以实现本次请求的取消  -> cancelAble.cancel() */
        CancelAble cancelAble = client.get(url, param, new OKRequestCallback() {
            public void onSuccess(String data) {
                Log.e("data",data);
            }

            public void onFailure(int httpCode) {
                Toast.makeText(MainActivity.this, "" + httpCode, Toast.LENGTH_SHORT).show();
            }
        });

    }

post 请求

   /* post 请求 */
    public void post(View view){
        RequestParam param = new RequestParam();
        param.add("pjlx","0");//岗位id
        CancelAble cancelAble = client.post(sds, param, new OKRequestCallback() {
            public void onSuccess(String data) {
                Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
                Log.e("data",data);
            }
            public void onFailure(int httpCode) {
                Toast.makeText(MainActivity.this, "" + httpCode+"", Toast.LENGTH_SHORT).show();
                Log.e("httpCode"," "+httpCode);
            }
        });
    }

上传文件

    /**
     *  上传文件
     *  */
    public void postFile(View view){
        RequestParam param = new RequestParam();
        File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");
        param.addFile("fileOptions.file",file);
        Log.e("aaa",file.toString()+"");
        Log.e("ddd",file.exists()+"");
        CancelAble cancelAble = client.post(url, param, new OKRequestCallback() {
            public void onSuccess(String data) {
                Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
                Log.e("data",data);
            }
            public void onFailure(int httpCode) {
                Log.e("httpCode",""+httpCode);
                Toast.makeText(MainActivity.this, httpCode+"", Toast.LENGTH_SHORT).show();
            }
        });
    }

下载

 /* 下载 */
    public void download(View view){
        final TextView tv = (TextView) view;
        String ren ="yumi";
        String url = "http://pic.qiantucdn.com/58pic/19/94/04/91U58PICT89_1024.jpg";
        File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ren+".jpg");
        while(file.exists()){
            i++;
            ren="yumi"+"("+i+")";
            file=null;
            file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ren+".jpg");
        }
        client.download(url, file
                , true /* 这个参数表示是否断线续传 */
                , new OKDownLoadCallback() {
                        public void onComplete(File file) {
                            Toast.makeText(MainActivity.this, "over", Toast.LENGTH_SHORT).show();
                        }
                        public void onError(int errCode) {
                            Toast.makeText(MainActivity.this, "error : "+ errCode , Toast.LENGTH_SHORT).show();
                        }
                        public void onProgress(int current) {
                                tv.setText(current+"");
                        }
        });

    }

以上汇报完毕,你最好包不要复制,不然会出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值