Okhttp的简单封装

本篇文章是对okhttp的一个简单封装 可以直接拿来用 代码中有相应的注释 鄙人菜鸟一个 没有什么太高深的思维
如有不足希望各位大佬指出
老规矩 闲话少说 先上代码

build.gradle中添加你的引用地址
不要忘了增加网络权限哟
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile ‘com.google.code.gson:gson:2.8.2’
先看看它的回调接口
public abstract class OkhttpReqCallBacek {

Type type;
static Type getSuperclassTypeParameter(Class subClass){
    Type superClass = subClass.getGenericSuperclass();
    if(superClass instanceof Class){
        throw new RuntimeException("Missing type parameter.");
    }
    ParameterizedType parameterizedType = (ParameterizedType)superClass;
    return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
}
public OkhttpReqCallBacek(){
    type = getSuperclassTypeParameter(getClass());
}
/**
 * 访问成功的回调
 **/
public abstract  void onSuccess(T result);
/*
 *访问失败的回调
*/
public abstract void onFail(String msg);
/**
 * 在请求之前的方法,一般用于加载框展示
 *
 * @param request
 */
public void onBefore(Request request) {
}
/**
 * 在请求之后的方法,一般用于加载框隐藏
 */
public void onAfter() {
}
/**
 * 进度条
 * @param pro
 */
public void onProgress(int pro){
}

}
接下来 建立自己的okhttp管理类 方便调用 我这里的方法大多采用public修饰 建议大家用private修饰 然后增加静态的公共方法 暴露给其他类调用
public class OkHttpManager {
public static final String TAG = “OkHttpManager”;
public static OkHttpManager instence;
private OkHttpClient okHttpClient;
private Handler okHttpHandler;

/**
 * 初始化OkHttpManager
 */
private OkHttpManager(Context context) {
    okHttpClient = new OkHttpClient().newBuilder()
            .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
            .readTimeout(10, TimeUnit.SECONDS) // 设置读取超时时间
            .writeTimeout(10, TimeUnit.SECONDS) // 设置写入超时时间
            .build();

    /**
     * 初始化handler
     */
    okHttpHandler = new Handler(context.getMainLooper());
}

/**
 * 获取单例引用
 */
public static OkHttpManager getInstance(Context context) {
    if (instence == null) {
        synchronized (OkHttpManager.class) {
            if (instence == null) {
                instence = new OkHttpManager(context);
            }
        }
    }
    return instence;
}

/**
 * okHttp get异步请求
 *
 * @param url      接口地址
 * @param callBack 请求返回数据回调
 * @param       数据泛型
 * @return
 */
public  Call getAsynHttp(String url, final OkhttpReqCallBacek callBack) {
    try {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                failedCallBack("访问失败", callBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    LogUtil.i("-----------返回结果:" + string);
                    successCallBack((T) string, callBack);
                } else {
                    failedCallBack("服务器错误", callBack);
                }
            }
        });
        return call;
    } catch (Exception e) {
    }
    return null;
}

/**
 * post请求
 *
 * @param url         请求地址
 * @param callBacek   接口回调
 * @param requestBody 请求参数
 * @param          泛型实体类
 * @return
 */
public  Call postAsynHttp(String url, final OkhttpReqCallBacek callBacek, RequestBody requestBody) {
    try {
        String httpUrl = HttpURL.HTTPURL + url;
        final Request request = new Request.Builder()
                .url(httpUrl)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                failedCallBack("访问失败", callBacek);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    LogUtil.i("短连接返回参数----"+string);
                    successCallBack((T) string, callBacek);
                } else {
                    failedCallBack("您访问到月球去了", callBacek);
                }
            }
        });
        return call;
    } catch (Exception e) {
        LogUtil.i("OkHttpManager------" + e);
    }
    return null;
}


/**
 * 异步post表单提交
 *
 * @param map       提交参数
 * @param url       请求地址
 * @param callBacek 网络访问回调
 * @param 
 * @return
 */
public  Call postFromBody(Map map, String url, final OkhttpReqCallBacek callBacek) {
    FormBody.Builder builder = new FormBody.Builder();
    for (String key : map.keySet()) {
        builder.add(key, map.get(key));
    }
    RequestBody formBody = builder.build();
    return postAsynHttp(url, callBacek, formBody);
}

/**
 * 异步json格式提交数据
 *
 * @param map       提交参数
 * @param url       请求地址
 * @param callBacek 网络访问回调
 * @param 
 */
public  Call postJson(Map map, String url, final OkhttpReqCallBacek callBacek) {
    StringBuilder stringBuilder = new StringBuilder();
    int pos = 0;
    for (String key : map.keySet()) {
        if (0 < pos) {
            stringBuilder.append("&");
        }
        stringBuilder.append(String.format("%s=%s", key, map.get(key)));
        pos++;
    }
    String jsonBody = stringBuilder.toString();
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody requestBody = RequestBody.create(JSON, jsonBody);
    return postAsynHttp(url, callBacek, requestBody);
}

/**
 * post上傳單張圖片
 *
 * @param file
 * @param url
 * @param callBacek
 * @param 
 * @return
 */
public  Call postImage(File file, String url, final OkhttpReqCallBacek callBacek) {
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
            .build();
    return postAsynHttp(url, callBacek, requestBody);
}

/**
 * @param url       下载连接
 * @param saveDir   储存下载文件的SDCard目录
 * @param callBacek 下载监听
 */
public  void download(final String url, final String saveDir, final OkhttpReqCallBacek callBacek) {
    Request request = new Request.Builder().url(url).build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // 下载失败
            failedCallBack("大哥 你把" + getNameFromUrl(url) + "下载到月球了", callBacek);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            InputStream is = null;
            byte[] buf = new byte[2048];
            int len = 0;
            FileOutputStream fos = null;
            // 储存下载文件的目录
            String savePath = isExistDir(saveDir);
            try {
                is = response.body().byteStream();
                long total = response.body().contentLength();
                File file = new File(savePath, getNameFromUrl(url));
                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);
                    // 下载中
                    OnProgress(progress, callBacek);
                }
                fos.flush();
                // 下载完成
                successCallBack((T) (getNameFromUrl(url) + "下载成功"), callBacek);
            } catch (Exception e) {
                failedCallBack(getNameFromUrl(url) + "下载异常" + e.toString(), callBacek);
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                }
            }
        }

    });
}

/**
 * 上传文件
 *
 * @param url      接口地址
 * @param filePath 本地文件地址
 */
public  void upLoadFile(String url, final String filePath, final OkhttpReqCallBacek callBack) {
    MediaType fileType = MediaType.parse("File/*");//数据类型为json格式,
    File file = new File(filePath);//file对象.
    RequestBody body = RequestBody.create(fileType, file);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            failedCallBack(filePath+"上传失败", callBack);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String string = response.body().string();
                successCallBack((T) string, callBack);
            } else {
                failedCallBack(filePath+"上传失败", callBack);
            }
        }
    });
}

/**
 * 统一处理成功信息
 *
 * @param result   返回结果
 * @param callBack 接口回调
 * @param       JSON的映射
 */
private  void successCallBack(final T result, final OkhttpReqCallBacek callBack) {
    okHttpHandler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack != null) {
                callBack.onSuccess(result);
            }
        }
    });
}

/**
 * 统一处理失败信息
 *
 * @param errorMsg
 * @param callBack
 * @param 
 */
private  void failedCallBack(final String errorMsg, final OkhttpReqCallBacek callBack) {
    okHttpHandler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack != null) {
                callBack.onFail(errorMsg);
            }
        }
    });
}
/**
 * 下载文件 返回进度条的值
 * @param pro
 * @param callBack
 * @param 
 */
private  void OnProgress(final int pro, final OkhttpReqCallBacek callBack) {
    okHttpHandler.post(new Runnable() {
        @Override
        public void run() {
            if (callBack != null) {
                callBack.onProgress(pro);
            }
        }
    });
}

}

你可能感兴趣的:(AndroidAPP)