Okhttp3封装

封装OKHTTP3一般的get,post请求,和文件下载,图片和多文件的上传。

package com.example.okhttpdemo;


import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author sk
 * @time 2018/7/16
 * @description okHTTP 封装类
 */
public class OkHttpUtil {
    private OkHttpClient okHttpClient;
    private Handler handler;
    private Gson gson;
    private static OkHttpUtil mInstance;
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    private OkHttpUtil() {
        //添加cookie
        okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);

            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        }).build();
        handler = new Handler(Looper.getMainLooper());
        gson = new Gson();
    }

    /**
     * 单例模式创建OkHttpUtil
     *
     * @return mInstance
     */
    public static OkHttpUtil getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpUtil.class) {
                mInstance = new OkHttpUtil();
            }
        }
        return mInstance;
    }

    /**
     * get 同步请求
     *
     * @return response
     */
    private Response _getDataSync(String url) {
        Request request = new Request.Builder()
                .get()//默认get,可省略
                .url(url)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * get 同步请求
     *
     * @return 字符串
     */
    private String _getDataString(String url) throws IOException {
        Response response = _getDataSync(url);
        if (response.body() != null) {
            return response.body().string();
        }
        return null;
    }

    /**
     * get 异步请求
     */
    private void _getDataAsync(String url, final ResultCallback callback) {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        deliveryResult(callback, request);
    }

    /**
     * post 同步请求
     *
     * @return response
     */
    private Response _postDataSync(String url, Param... params) throws IOException {
        Request request = buildPostRequest(url, params);
        return okHttpClient.newCall(request).execute();

    }

    /**
     * post 同步请求
     *
     * @return 字符串
     */
    private String _postDataString(String url, Param... params) throws IOException {
        Response response = _postDataSync(url, params);
        return response.body().string();
    }

    /**
     * post 异步请求
     */
    private void _postDataAsync(String url, final ResultCallback callback, Param... params) {
        Request request = buildPostRequest(url, params);
        deliveryResult(callback, request);

    }

    /**
     * post 异步请求
     */

    private void _postDataAsync(String url, final ResultCallback callback, Map<String, String> params) {
        Param[] paramsArr = map2Params(params);
        Request request = buildPostRequest(url, paramsArr);
        deliveryResult(callback, request);
    }

    /**
     * post 同步文件上传
     */
    private Response _postDataFileSync(String url, File[] files, String[] fileKeys, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        return okHttpClient.newCall(request).execute();
    }

    private Response _postDataFileSync(String url, File file, String fileKey) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        return okHttpClient.newCall(request).execute();
    }

    private Response _postDataFileSync(String url, File file, String fileKey, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        return okHttpClient.newCall(request).execute();
    }

    /**
     * 异步基于post的多文件上传
     */
    private void _postDataFileAsync(String url, final ResultCallback callback, File[] files, String[] fileKeys, Param... params) {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        deliveryResult(callback, request);
    }

    /**
     * 异步基于post的文件上传,单文件不带参数上传
     *
     * @param url
     * @param callback
     * @param file
     * @param fileKey
     */
    private void _postDataFileAsync(String url, ResultCallback callback, File file, String fileKey) {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        deliveryResult(callback, request);
    }

    /**
     * 异步基于post的文件上传,单文件且携带其他form参数上传
     *
     * @param url      接口地址
     * @param callback callback
     * @param file     file
     * @param fileKey  fileKey
     * @param params   params
     */
    private void _postDataFileAsync(String url, ResultCallback callback, File file, String fileKey, Param... params) {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        deliveryResult(callback, request);
    }

    /**
     * 同步 post上传json对象
     *
     * @param url     url;
     * @param jsonStr json 字符串
     * @return 字符串
     * @throws IOException
     */
    private String _postJsonDataSync(String url, String jsonStr) throws IOException {
        String result = null;
        MediaType JSON = MediaType.parse("text/html;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonStr);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = okHttpClient.newCall(request).execute();
        result = response.body().string();
        return result;
    }

    /**
     * 异步 post上传json对象
     *
     * @param url      url
     * @param jsonStr  json数据字符串
     * @param callback callback
     */
    private void _postJsonDataAsync(String url, String jsonStr, final ResultCallback callback) {
        MediaType JSON = MediaType.parse("text/html;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonStr);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        deliveryResult(callback, request);
    }

    /**
     * post 异步上传图片
     *
     * @param url      url
     * @param callback callback
     * @param file     file
     * @param fileKey  fileKey
     * @param map      map
     */
    private void _upLoadImg(String url, final ResultCallback callback, File file, String fileKey, Map<String, String> map) {
        Param[] params = map2Params(map);
        getInstance()._postDataFileAsync(url, callback, file, fileKey, params);
    }

    /**
     * 创建 MultipartFormRequest
     *
     * @param url      接口地址
     * @param files    files
     * @param fileKeys file keys
     * @param params   params
     * @return MultipartFormRequest
     */

    private Request buildMultipartFormRequest(String url, File[] files,
                                              String[] fileKeys, Param[] params) {
        params = validateParam(params);

        MultipartBody.Builder builder = new MultipartBody.Builder();
        for (Param param : params) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                    RequestBody.create(null, param.value));
        }
        if (files != null) {
            RequestBody fileBody;
            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();
    }

    private Param[] validateParam(Param[] params) {
        if (params == null)
            return new Param[0];
        else
            return params;
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 异步下载文件
     */
    private void _downloadFileAsync(final String url, final String destFileDir,
                                    final ResultCallback callback) {
        final Request request = new Request.Builder().url(url).build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] b = new byte[2048];
                int len;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(destFileDir, getFileName(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                    }
                    fos.flush();
                    // 如果下载文件成功,第一个参数为文件的绝对路径
                    sendSuccessResultCallback(file.getAbsolutePath(), callback);
                } catch (Exception e) {
                    sendFailedStringCallback(response.request(), e, callback);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                }
            }

        });
    }

    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1,
                path.length());
    }

    /***************************************************************** 公共方法***************************************************/
    /**
     * get 同步请求
     *
     * @param url 接口地址
     * @return response
     */
    public static Response getDataSync(String url) {
        return getInstance()._getDataSync(url);
    }

    /**
     * get 同步请求
     *
     * @param url 接口地址
     * @return 字符串
     * @throws IOException
     */
    public static String getDataString(String url) throws IOException {
        return getInstance()._getDataString(url);
    }

    /**
     * get 异步请求
     *
     * @param url 接口地址
     */
    public static void getDataAsync(String url, final ResultCallback callback) {
        getInstance()._getDataAsync(url, callback);
    }

    /**
     * post 同步请求
     *
     * @param url   url
     * @param param param
     * @return response
     * @throws IOException
     */
    public static Response postDataSync(String url, Param... param) throws IOException {
        return getInstance()._postDataSync(url, param);
    }

    /**
     * post 同步请求
     *
     * @param url    url
     * @param params param
     * @return 字符串
     * @throws IOException
     */
    public static String postDataString(String url, Param... params) throws IOException {
        return getInstance()._postDataString(url, params);
    }

    /**
     * post 异步请求
     *
     * @param url      url
     * @param callback 异步回调
     * @param params   params
     */
    public static void postDataAsync(String url, final ResultCallback callback, Param... params) {
        getInstance()._postDataAsync(url, callback, params);
    }

    /**
     * post map集合 异步请求
     *
     * @param url      url
     * @param callback callback
     * @param params   params
     */
    public static void postDataAsync(String url, final ResultCallback callback, Map<String, String> params) {
        getInstance()._postDataAsync(url, callback, params);
    }

    /**
     * post 异步上传图片
     *
     * @param url      url
     * @param callback callback
     * @param file     file
     * @param fileKey  fileKey
     * @param map      map
     */
    public static void upLoadImg(String url, final ResultCallback callback, File file, String fileKey, Map<String, String> map) {
        getInstance()._upLoadImg(url, callback, file, fileKey, map);
    }

    /**
     * map 转换为 Param
     *
     * @param params map
     * @return params
     */
    private Param[] map2Params(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;
    }

    /**
     * 创建 PostRequest
     *
     * @param url    url
     * @param params params
     * @return request
     */
    private Request buildPostRequest(String url, Param[] params) {
        if (params == null) {
            params = new Param[0];
        }
        FormBody.Builder builder = new FormBody.Builder();
        for (Param param : params) {
            builder.add(param.key, param.value);
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }


    /**
     * 抽象类,用于请求成功后的回调
     *
     * @param <T>
     */
    public static abstract class ResultCallback<T> {
        //这是请求数据的返回类型,包含常见的(Bean,List等)
        Type mType;

        public ResultCallback() {
            mType = getSuperclassTypeParameter(getClass());
        }

        /**
         * 通过反射想要的返回类型
         *
         * @param subclass
         * @return
         */
        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 abstract void onError(Request request, Exception e);

        //成功的回调
        public abstract void onResponse(T response);
    }

    private Map<String, String> mSessions = new HashMap<>();

    /**
     * 请求回调处理方法并传递返回值
     *
     * @param callback Map类型请求参数
     * @param request  Request请求
     */
    private void deliveryResult(final ResultCallback callback, final Request request) {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final String string = response.body().string();
                    if (callback.mType == String.class) {
                        sendSuccessResultCallback(string, callback);
                    } else {
                        Object o = gson.fromJson(string, callback.mType);
                        sendSuccessResultCallback(o, callback);
                    }


                } catch (IOException e) {
                    sendFailedStringCallback(response.request(), e, callback);
                } catch (com.google.gson.JsonParseException e)//Json解析的错误
                {
                    sendFailedStringCallback(response.request(), e, callback);
                }
            }

        });
    }

    /**
     * 处理请求失败的回调信息方法
     *
     * @param e        错误信息
     * @param callback 回调类
     */
    private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(request, e);
            }
        });
    }

    /**
     * 处理请求成功的回调信息方法
     *
     * @param object   服务器响应信息
     * @param callback 回调类
     */
    private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(object);
                }
            }
        });
    }

    public static class Param {
        public Param() {
        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }

        String key;
        String value;
    }

  
}

参考链接:https://blog.csdn.net/lmj623565791/article/details/47911083

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