Android 的OkHttp 网络请求框架的封装学习

以前写过一些东西,但是写写不看不用就容易忘掉,今天写写东西记下来,有空的时候多温习温习
OkHttp 分为同步和异步请求;请求方式常用的有 get和post两种方式,封装请求的大致步骤为:
1、首先 创建 一个mOkHttpClient = new OkHttpClient()对象;
2、构建Request请求对象(根据get和post不同的请求方式分别创建);
3、如果是 post请求还需要 构建 请求参数 Params,RequestBody requestBody = buildFormData(params); builder.post(requestBody).build;;
4、进行网络异步请求 mOkHttpClient.newCall(request).enqueue(new Callback() {} ),如果是同步请求,则改为 Response response = mOkHttpClient.newCall(request).execute()进行 ;
具体实现就不细说了,直接上代码如下:

public class OkHttpManager {
 
    private static OkHttpManager mOkHttpManager;
 
    private OkHttpClient mOkHttpClient;
 
    private Gson mGson;
 
    private Handler handler;
 
    private OkHttpManager() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS);
        mGson = new Gson();
        handler = new Handler(Looper.getMainLooper());
    }
 
    //创建 单例模式(OkHttp官方建议如此操作)
    public static OkHttpManager getInstance() {
        if (mOkHttpManager == null) {
            mOkHttpManager = new OkHttpManager();
        }
        return mOkHttpManager;
    }
 
    /***********************
     * 对外公布的可调方法
     ************************/
 
    public void getRequest(String url, final BaseCallBack callBack) {
        Request request = buildRequest(url, null, HttpMethodType.GET);
        doRequest(request, callBack);
    }
 
    public void postRequest(String url, final BaseCallBack callBack, Map<String, String> params) {
        Request request = buildRequest(url, params, HttpMethodType.POST);
        doRequest(request, callBack);
    }
 
    public void postUploadSingleImage(String url, final BaseCallBack callback, File file, String fileKey, Map<String, String> params) {
        Param[] paramsArr = fromMapToParams(params);
 
        try {
            postAsyn(url, callback, file, fileKey, paramsArr);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    public void postUploadMoreImages(String url, final BaseCallBack callback, File[] files, String[] fileKeys, Map<String, String> params) {
        Param[] paramsArr = fromMapToParams(params);
 
        try {
            postAsyn(url, callback, files, fileKeys, paramsArr);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    /***********************
     * 对内方法
     ************************/
    //单个文件上传请求  不带参数
    private void postAsyn(String url, BaseCallBack callback, File file, String fileKey) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        doRequest(request, callback);
    }
 
    //单个文件上传请求 带参数
    private void postAsyn(String url, BaseCallBack callback, File file, String fileKey, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        doRequest(request, callback);
    }
 
    //多个文件上传请求 带参数
    private void postAsyn(String url, BaseCallBack callback, File[] files, String[] fileKeys, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        doRequest(request, callback);
    }
 
    //异步下载文件
    public void asynDownloadFile(final String url, final String destFileDir, final BaseCallBack callBack) {
        final Request request = buildRequest(url, null, HttpMethodType.GET);
        callBack.OnRequestBefore(request);  //提示加载框
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e);
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                callBack.onResponse(response);
 
                InputStream is = null;
                byte[] buf = new byte[1024*2];
                final long fileLength = response.body().contentLength();
                int len = 0;
                long readLength = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(destFileDir, getFileName(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        readLength += len;
                        int curProgress = (int) (((float) readLength / fileLength) * 100);
                        Log.e("lgz", "onResponse: >>>>>>>>>>>>>" + curProgress + ", readLength = " + readLength + ", fileLength = " + fileLength);
                        callBack.inProgress(curProgress, fileLength, 0);
                    }
                    fos.flush();
                    //如果下载文件成功,第一个参数为文件的绝对路径
                    callBackSuccess(callBack, call, response, file.getAbsolutePath());
                } catch (IOException e) {
                    callBackError(callBack, call, response.code());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
 
 
    }
 
    //构造上传图片 Request
    private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) {
        params = validateParam(params);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Param param : params) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                    RequestBody.create(MediaType.parse("image/png"), param.value));
        }
        if (files != null) {
            RequestBody fileBody = null;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();
                fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
                //TODO 根据文件名设置contentType
                builder.addPart(Headers.of("Content-Disposition",
                        "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                        fileBody);
            }
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }
    //Activity页面所有的请求以Activity对象作为tag,可以在onDestory()里面统一取消,this
    public void cancelTag(Object tag) {
        for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }
    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }
    private Param[] fromMapToParams(Map<String, String> params) {
        if (params == null)
            return new Param[0];
        int size = params.size();
        Param[] res = new Param[size];
        Set<Map.Entry<String, String>> entries = params.entrySet();
        int i = 0;
        for (Map.Entry<String, String> entry : entries) {
            res[i++] = new Param(entry.getKey(), entry.getValue());
        }
        return res;
    }
 
    //去进行网络 异步 请求
    private void doRequest(Request request, final BaseCallBack callBack) {
        callBack.OnRequestBefore(request);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e);
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callBack.onResponse(response);
                String result = response.body().string();
                if (response.isSuccessful()) {
 
                    if (callBack.mType == String.class) {
//                        callBack.onSuccess(call, response, result);
                        callBackSuccess(callBack, call, response, result);
                    } else {
                        try {
                            Object object = mGson.fromJson(result, callBack.mType);//自动转化为 泛型对象
//                            callBack.onSuccess(call, response, object);
                            callBackSuccess(callBack, call, response, object);
                        } catch (JsonParseException e) {
                            //json解析错误时调用
                            callBack.onEror(call, response.code(), e);
                        }
 
                    }
                } else {
                    callBack.onEror(call, response.code(), null);
                }
 
            }
 
        });
 
 
    }
 
    //创建 Request对象
    private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) {
 
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (methodType == HttpMethodType.GET) {
            builder.get();
        } else if (methodType == HttpMethodType.POST) {
            RequestBody requestBody = buildFormData(params);
            builder.post(requestBody);
        }
        return builder.build();
    }
 
    //构建请求所需的参数表单
    private RequestBody buildFormData(Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("platform", "android");
        builder.add("version", "1.0");
        builder.add("key", "123456");
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        return builder.build();
    }
 
    private void callBackSuccess(final BaseCallBack callBack, final Call call, final Response response, final Object object) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onSuccess(call, response, object);
            }
        });
 
    }
 
    private void callBackError(final BaseCallBack callBack, final Call call, final int code) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onEror(call, code, null);
            }
        });
 
    }
 
    private Param[] validateParam(Param[] params) {
        if (params == null)
            return new Param[0];
        else
            return params;
    }
 
    public static class Param {
        public Param() {
        }
 
        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }
 
        String key;
        String value;
    }
 
    enum HttpMethodType {
        GET, POST
    }
 
 
}

其中的 BaseCallBack回调机制封装如下:

public abstract class BaseCallBack<T> {
    public Type mType;
 
    static Type getSuperclassTypeParameter(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }
 
 
    public BaseCallBack() {
        mType = getSuperclassTypeParameter(getClass());
    }
 
    protected abstract void OnRequestBefore(Request request);
 
    protected abstract void onFailure(Call call, IOException e);
 
    protected abstract void onSuccess(Call call, Response response, T t);
 
    protected abstract void onResponse(Response response);
 
    protected abstract void onEror(Call call, int statusCode, Exception e);
 
    protected abstract void inProgress(int progress, long total , int id);
}

上面这个类OkHttpManager 是我根据网络上各家资源学习封装好的,copy进代码可以直接使用,并且根据okhttp3.0以后的版本,对之前的一下请求参数设置进行了最新的修改,具体如下:

1、设置请求超时参数;

okhttp3.0以前的版本是这样设置的

new OkHttpClient();

mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);

mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);

mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);

之后的版本是这样设置的:

new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间

2、post方式请求时,构建表单对象参数;

okhttp3.0以前的版本是这样构建的:new FormEncodingBuilder()对象,然后向里面add (key,value)参数;

之后的版本更改为:FormBody body = new FormBody.Builder(),.add(key, value);即是FormEncodingBuilder已被FormBody取代;

至于BaseCallBack类,根据请求数据的功能的不同,还需要对此进行封装,集成自己需要的方法实现;

一、进行一般的数据加载请求,可直接调用如下:

模拟用户登录:

Map<String, String> params = new HashMap<String, String>();
                    params.put("Mobile", username.getText().toString());
                    params.put("PassWord", password.getText().toString());
 
                    OkHttpManager.getInstance().postRequest(Constants.LOGIN_URL, new LoadCallBack<String>(getActivity()) {
                                @Override
                                protected void onSuccess(Call call, Response response, String s) {
                                    Log.e("lgz", "onSuccess = " + s);
                                    Toast.makeText(getActivity(), "登录成功!", Toast.LENGTH_LONG).show();
                                }
 
                                @Override
                                protected void onEror(Call call, int statusCode, Exception e) {
                                    Log.e("lgz", "Exception = " + e.toString());
                                }
                            }
                            , params);

上面登录请求中 就用到了自己根据需要再次封装的Callback类的继承实现,LoadCallBack<T>类:

//添加对请求时对话框的处理
public abstract class LoadCallBack<T> extends BaseCallBack<T> {
    private Context context;
    private SpotsDialog spotsDialog;
 
    public LoadCallBack(Context context) {
        this.context = context;
        spotsDialog = new SpotsDialog(context);
    }
 
    private void showDialog() {
        spotsDialog.show();
    }
 
    private void hideDialog() {
        if (spotsDialog != null) {
            spotsDialog.dismiss();
        }
    }
 
    public void setMsg(String str) {
        spotsDialog.setMessage(str);
    }
 
    public void setMsg(int  resId) {
        spotsDialog.setMessage(context.getString(resId));
    }
 
 
    @Override
    protected void OnRequestBefore(Request request) {
        showDialog();
 
    }
 
    @Override
    protected void onFailure(Call call, IOException e) {
        hideDialog();
    }
 
    @Override
    protected void onResponse(Response response) {
        hideDialog();
    }
 
    @Override
    protected void inProgress(int progress, long total, int id) {
 
    }

其实这个类就是对BaseCallBack再次继承实现;
二、下载文件,并显示进度条对话框的请求操作:

下载一张图片:


OkHttpManager.getInstance().asynDownloadFile("http://www.7mlzg.com/uploads/bwf_1477419976.jpg", FILE_PATH, new FileCallBack<String>(getActivity()) {
                    @Override
                    protected void onResponse(Response response) {
 
                    }
 
                    @Override
                    protected void onSuccess(Call call, Response response, String s) {
                        super.onSuccess(call, response, s);
                        Log.e("lgz", "status = : " + s);
                        Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(new File(s));//广播通知系统图集更新
                        intent.setData(uri);
                        getActivity().sendBroadcast(intent);
                    }
                });

上面下载图片中,就用到了自己根据需要再次继承Callback类封装得到的FileCallBack<T>类如下:

public abstract class FileCallBack<T> extends BaseCallBack<T> {
 
    private Context mContext;
 
    private ProgressDialog mProgressDialog;
 
    public FileCallBack(Context context) {
        mContext = context;
        initDialog();
    }
 
    private void initDialog(){
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setTitle("下载中...");
        mProgressDialog.setCanceledOnTouchOutside(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
    }
 
    private void hideDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
 
    @Override
    protected void OnRequestBefore(Request request) {
        mProgressDialog.show();
    }
 
    @Override
    protected void onFailure(Call call, IOException e) {
       hideDialog();
    }
 
    @Override
    protected void onSuccess(Call call, Response response, T t) {
        Log.e("lgz", "onSuccess: >>>>>>>>>>>>>");
        hideDialog();
    }
 
    @Override
    protected void onEror(Call call, int statusCode, Exception e) {
        hideDialog();
    }
 
    @Override
    protected void inProgress(int progress, long total, int id) {
        Log.e("lgz", "inProgress: >>>>>>>>>>>>>"+progress);
        mProgressDialog.setProgress(progress);
 
    }
}

三、最后说一下使用okhttp的配置:
在Android Studio 中,直接在build.gradle文件里配置 :compile 'com.squareup.okhttp3:okhttp:3.4.1'

在Eclipse里需要导入jar包使用,下载最新jar;

当然了,这里只是对Okhttp常用的一些功能进行了封装处理,使用的都是异步请求方式,至于同步操作,我个人觉得不是很常用,使用时需要开启一个线程,不然会阻塞UI线程的;最后,这只是一个简单的学习,其中要是有不足和错误,还希望大家留言批评指正,谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容