okhttp封装

Okhttp 是一个 android 网络请求框架,如果不进行封装 调用会超麻烦,就会有大量的重复代码。

思路:分别封装 get,post,put,delete 请求,设置 interface 完成与失败 的 方法供外部自己实现

经过封装好OkhttpHelper的就可以下面这样调用, 只需要写成功与失败的逻辑了。

OkhttpHelper okhttpHelper = new OkhttpHelper();
Map<String, String> map = new HashMap<String, String>();
map.put("test", "fuck");
map.put("af", "你好");
okhttpHelper.get("dynamic", map, new OkhttpHelper.listener() {
    @Override
    public void onSuccess(String response) {
        Log.e("this", response);
    }

    @Override
    public void onError() {

    }
});

下面是OkhttpHelper 复制粘贴吧,
提醒:记得改下面类属性host 你自己的主机

/**
 * @date: 2019/4/21
 * @author:bin
 * @email:[email protected]
 */
public class OkhttpHelper {

    private String host = "http://10.0.2.2:8080/lzy/";//主机地址
//    private String host = "http://127.0.0.1:8080/lzy/";//主机地址

    /**
     *  GET 请求
     * @param url 请求地址
     * @param params 请求参数
     * @param listener 成功与失败监听
     */
    public void get(final String url, final Map<String, String> params, final listener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//OkHttpClient对象
                    StringBuffer paramStr = new StringBuffer("");
                    if (params != null) {//构建请求参数
                        paramStr.append("?");
                        for (String key:params.keySet()) {
                            paramStr.append(key + "=" + URLEncoder.encode(params.get(key), "utf-8") + "&");
                        }
                       paramStr.deleteCharAt(paramStr.length() - 1);//删掉最后一个&
                        Log.e("this", paramStr.toString());
                    }

                    Request request = new Request.Builder()
                            .url(host + url + paramStr)
                            .get()
                            .build();//创建Request 对象

                    Response response = null;
                    response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.d("kwwl","response.code()=="+response.code());
                        Log.d("kwwl","response.message()=="+response.message());
                        listener.onSuccess(response.body().string());
                    } else {
                        listener.onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * post 请求
     * @param url
     * @param params
     * @param listener
     */
    public void post(final String url, final Map<String, String> params, final listener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//OkHttpClient对象
                    FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                    StringBuffer paramStr = new StringBuffer("");
                    if (params != null) {//构建请求参数
                        for (String key:params.keySet()) {
                            formBody.add("key", params.get(key));
                        }
                    }

                    Request request = new Request.Builder()
                            .url(host + url + paramStr)
                            .post(formBody.build())
                            .build();//创建Request 对象

                    Response response = null;
                    response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        listener.onSuccess(response.body().string());
                    } else {
                        listener.onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * put 请求
     * @param url
     * @param params
     * @param listener
     */
    public void put(final String url, final Map<String, String> params, final listener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//OkHttpClient对象
                    FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                    StringBuffer paramStr = new StringBuffer("");
                    if (params != null) {//构建请求参数
                        for (String key:params.keySet()) {
                            formBody.add("key", params.get(key));
                        }
                    }

                    Request request = new Request.Builder()
                            .url(host + url + paramStr)
                            .put(formBody.build())
                            .build();//创建Request 对象

                    Response response = null;
                    response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        listener.onSuccess(response.body().string());
                    } else {
                        listener.onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * delete 请求
     * @param url
     * @param params
     * @param listener
     */
    public void delete(final String url, final Map<String, String> params, final listener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//OkHttpClient对象
                    FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                    StringBuffer paramStr = new StringBuffer("");
                    if (params != null) {//构建请求参数
                        for (String key:params.keySet()) {
                            formBody.add("key", params.get(key));
                        }
                    }

                    Request request = new Request.Builder()
                            .url(host + url + paramStr)
                            .delete(formBody.build())
                            .build();//创建Request 对象

                    Response response = null;
                    response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        listener.onSuccess(response.body().string());
                    } else {
                        listener.onError();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public interface listener {
        void onSuccess(String response);
        void onError();
    }

}

你可能感兴趣的:(android_util)