浅谈android开发中的的OkHttpUtils

okhttputils 是csdn 鸿洋大神基于okhttp网络请求进行的二次封装,相比较其他的如retrofit框架本人还是喜欢用hongyang大神的okhttputils只是结合自身情况做一些简单的修改便可。当然了两种框架到底谁好就仁者见仁智者见智了。废话少说直接上代码,带你们一步一步了解用法。

1.在你的app gradle添加依赖 compile ‘com.zhy:okhttputils:2.6.2’(具体的最新版本请去github)
2.在你项目的application下初始化
public class MyApplication extends Application{
    public static MyApplication instance;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private DaoMaster.DevOpenHelper mHelper;

    public static  synchronized MyApplication getInstances() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance=this;
        initHttpUtils();//初始化okhttputils

        // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, "cadillac-db", null);
        db = mHelper.getWritableDatabase();
        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();

    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
    public SQLiteDatabase getDb() {
        return db;
    }

    /**
     * 初始化
     */
    private void initHttpUtils() {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10000L, TimeUnit.MILLISECONDS)//设置链接超时
                    .readTimeout(100000L, TimeUnit.MILLISECONDS)//设置读取超时
                    .build();
            OkHttpUtils.initClient(okHttpClient);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }

3.自定义一个抽象类,申明两个抽象的方法作为你在界面发送请求时候的回掉(调取成功或失败)

package cadillac.example.com.cadillac.http;
import com.google.gson.internal.$Gson$Types;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public  abstract class ResultCallback<T> {
    public Type mType;

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

    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(int status,String errorMsg);

    public abstract void onResponse(T response);

    }

4.创建请求管理类OkHttpManager,里面封装请求的post方法,get方法等..

public class OkHttpManager {
    private static OkHttpClient mOkHttpClient;
    private okhttp3.Headers headers;
    private static OkHttpManager mInstance;
    private Gson mGson;
    private Handler mDelivery;

    public OkHttpManager() {
        mGson = new Gson();
        //        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        mOkHttpClient = builder.build();
        //cookie enabled
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public static OkHttpManager getInstance() {
        if (mInstance == null) {
            if (mInstance == null) {
                mInstance = new OkHttpManager();
            }
        }
        return mInstance;
    }

    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;
    }

    /**
     * post请求  键值对
     *
     * @param url
     * @param paramMap
     * @param callback
     */
    public void doPost(String url, Map<String, String> paramMap, final ResultCallback callback) {
        MyLogUtils.info("请求地址:" + url);
        MyLogUtils.info("请求参数:" + GsonUtils.bean2Json(paramMap));
        OkHttpUtils.post().url(url).params(paramMap).headers(getHeaders()).build().execute(new   com.zhy.http.okhttp.callback.Callback<String>() {
            @Override
            public String parseNetworkResponse(Response response, int id) throws Exception {
                String header = response.header("Set-Cookie");
                MyLogUtils.info("获取到cookie:" + header);
                if (!TextUtils.isEmpty(header))
                    SpUtils.setCooike(MyApplication.getInstances(), header);
                return response.body().string();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                sendFailedStringCallback(-1, "请求失败,请检查网络!", callback);
            }

            @Override
            public void onResponse(String result, int id) {
                MyLogUtils.info("获取result:" + result);
                if (callback.mType == String.class) {
                    sendSuccessResultCallback(result, callback);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.equals("success")) {//成功
                            Object o = mGson.fromJson(result, callback.mType);
                            sendSuccessResultCallback(o, callback);
                        }else {//失败
                            sendFailedStringCallback(-1, jsonObject.getString("message"), callback);
                        }
                    } catch (Exception e) {
                        sendFailedStringCallback(-1, "解析异常", callback);
                    }
                }

            }
        });
    }




    /**
     * post请求只是参数全部转成json
     *
     * @param url
     * @param paramMap
     * @param callback
     */
    public void doPostForjson(String url, Map<String, String> paramMap, final ResultCallback callback) {
        MyLogUtils.info("请求地址:" + url);
        MyLogUtils.info("请求参数:" + GsonUtils.bean2Json(paramMap));
        OkHttpUtils.postString().
                url(url).
                mediaType(MediaType.parse(("application/json; charset=utf-8;"))
                ).headers(getHeaders()).
                content(GsonUtils.bean2Json(paramMap)).build().
                execute(new com.zhy.http.okhttp.callback.Callback<String>() {
                    @Override
                    public String parseNetworkResponse(Response response, int id) throws Exception {
                        String header = response.header("Set-Cookie");
                        MyLogUtils.info("获取到cookie:" + header);
                        if (!TextUtils.isEmpty(header))
                            SpUtils.setCooike(MyApplication.getInstances(), header);
                        return response.body().string();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        sendFailedStringCallback(-1, "请求失败,请检查网络!", callback);
                    }

                    @Override
                    public void onResponse(String result, int id) {
                        MyLogUtils.info("获取result:" + result);
                        if (callback.mType == String.class) {
                            sendSuccessResultCallback(result, callback);
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String succ = jsonObject.getString("code");
                                if (succ.equals("success")) {//成功
                                    Object o = mGson.fromJson(result, callback.mType);
                                    sendSuccessResultCallback(o, callback);
                                }
//                        else if (status == 601) {
//                            sendFailedStringCallback(status, result, callback);
//                        }
                                else {//失败
                                    sendFailedStringCallback(400, jsonObject.getString("message"), callback);
                                }
                            } catch (Exception e) {
                                sendFailedStringCallback(-1, "解析异常", callback);
                            }
                        }
                    }
                });
    }

    /**
     * get请求  键值对
     *
     * @param url
     * @param paramMap
     * @return
     */
    public void doGet(String url, Map<String, String> paramMap, final ResultCallback callback) {
        MyLogUtils.info("请求地址:" + url);
        MyLogUtils.info("请求参数:" + GsonUtils.bean2Json(paramMap));
        OkHttpUtils.get().url(url).params(paramMap).headers(getHeaders()).build().execute(new com.zhy.http.okhttp.callback.Callback<String>() {
            @Override
            public String parseNetworkResponse(Response response, int id) throws Exception {
                String header = response.header("Set-Cookie");
                MyLogUtils.info("获取到cookie:" + header);
                if (!TextUtils.isEmpty(header))
                    SpUtils.setCooike(MyApplication.getInstances(), header);
                return response.body().string();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                sendFailedStringCallback(-1, "请求失败,请检查网络!", callback);
            }

            @Override
            public void onResponse(String result, int id) {
                MyLogUtils.info("获取result:" + result);
                if (callback.mType == String.class) {
                    sendSuccessResultCallback(result, callback);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.equals("success")) {//成功
                            Object o = mGson.fromJson(result, callback.mType);
                            sendSuccessResultCallback(o, callback);
                        }else {//失败
                            sendFailedStringCallback(-1, jsonObject.getString("message"), callback);
                        }
                    } catch (Exception e) {
                        sendFailedStringCallback(-1, "解析异常", callback);
                    }
                }
            }
        });

    }
   //自己申明的回掉方法
      private void sendFailedStringCallback(final int status, final String e, final ResultCallback callback) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(status, e);
            }
        });
    }

    private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(object);
                }
            }
        });
    }


    /**
     * post请求只是参数全部转成jsonlist
     *
     * @param url
     * @param
     * @param callback
     */
    public void doPostForjsonfromList(String url, List<LoadBean>list, final ResultCallback callback) {
        MyLogUtils.info("请求地址:" + url);
        MyLogUtils.info("请求参数:" + GsonUtils.bean2Json(list));
        OkHttpUtils.postString().
                url(url).
                mediaType(MediaType.parse(("application/json; charset=utf-8;"))
                ).headers(getHeaders()).content(GsonUtils.bean2Json(list)).build().
                execute(new com.zhy.http.okhttp.callback.Callback<String>() {
                    @Override
                    public String parseNetworkResponse(Response response, int id) throws Exception {
                        String header = response.header("Set-Cookie");
                        MyLogUtils.info("获取到cookie:" + header);
                        if (!TextUtils.isEmpty(header))
                            SpUtils.setCooike(MyApplication.getInstances(), header);
                        return response.body().string();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        sendFailedStringCallback(-1, "请求失败,请检查网络!", callback);
                    }

                    @Override
                    public void onResponse(String result, int id) {
                        MyLogUtils.info("获取result:" + result);
                        if (callback.mType == String.class) {
                            sendSuccessResultCallback(result, callback);
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String succ = jsonObject.getString("code");
                                if (succ.equals("success")) {//成功
                                    Object o = mGson.fromJson(result, callback.mType);
                                    sendSuccessResultCallback(o, callback);
                                }
//                        else if (status == 601) {
//                            sendFailedStringCallback(status, result, callback);
//                        }
                                else {//失败
                                    sendFailedStringCallback(400, jsonObject.getString("message"), callback);
                                }
                            } catch (Exception e) {
                                sendFailedStringCallback(-1, "解析异常", callback);
                            }
                        }
                    }
                });
    }


    /**
     * 上传图片
     *
     * @param url
     * @param params
     * @param files
     * @param callback
     */
    public void uploadFile(final String url, Map<String, String> params, Map<String, File> files, final ResultCallback callback) {
        MyLogUtils.info("参数URL:" + url);
        MyLogUtils.info("参数paramms:" + params);
        MyLogUtils.info("参数files:" + files);
        OkHttpUtils.post().url(url).params(params).headers(getHeaders()).files("file", files).build().execute(new com.zhy.http.okhttp.callback.Callback<String>() {

            @Override
            public String parseNetworkResponse(Response response, int id) throws Exception {
                String header = response.header("Set-Cookie");
                MyLogUtils.info("获取到cookie:" + header);
                if (!TextUtils.isEmpty(header))
                    SpUtils.setCooike(MyApplication.getInstances(), header);
                return response.body().string();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                sendFailedStringCallback(-1, "请求失败,请检查网络!", callback);
            }

            @Override
            public void onResponse(String result, int id) {
                MyLogUtils.info("获取result:" + result);
                if (callback.mType == String.class) {
                    sendSuccessResultCallback(result, callback);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        int status = jsonObject.getInt("status");
                        if (status == 200) {//成功
                            Object o = mGson.fromJson(result, callback.mType);
                            sendSuccessResultCallback(o, callback);
                        } else if (status == 601) {
                            sendFailedStringCallback(status, result, callback);
                        } else {//失败
                            sendFailedStringCallback(status, jsonObject.getString("message"), callback);
                        }
                    } catch (Exception e) {
                        sendFailedStringCallback(-1, "解析异常", callback);
                    }
                }
            }
        });
    }






    /**
     * 获取请求头
     *
     * @param
     * @return //
     */
    public static Map<String, String> getHeaders() {
        HashMap<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(SpUtils.getCookie(MyApplication.getInstances()))) {
            map.put("Cookie", SpUtils.getCookie(MyApplication.getInstances()));
        }
//        if (EchinfoUtils.getCurrentUser() != null) {
//            if (!TextUtils.isEmpty(EchinfoUtils.getCurrentUser().getId())) {
//                map.put("keyUserId", EchinfoUtils.getCurrentUser().getId());
//            }
//        }
//        map.put("Content-Type","application/x-www-form-urlencoded");//注册当中的请求头
        return map;
    }


    }

5.创建一个类,申明你自己的方法。比如登录,注册,查询等….示例代码如下

public class UserManager {
    private static UserManager userManager;

    public static UserManager getUserManager() {
        if (userManager == null) {
            userManager = new UserManager();
        }
        return userManager;
    }

    /**登录接口
     * @param
     * @param
     * @param
     * @param
     * @param resultCallback
     */
    public void toLogin(String userName,String password,ResultCallback resultCallback){
        Map<String, String> params = new HashMap<>();
        params.put("userName",userName);
        params.put("password",password);

        OkHttpManager.getInstance().doPostForjson(CadillacUrl.LOGIN_URL,params,resultCallback);
    }
    }
展开阅读全文

没有更多推荐了,返回首页