android okhttp3的封装

最近由于苦逼的学校课程,我们需要用android开发一款教学辅助软件,所以我就开始看android开发的相关知识,今天实战的时候发现okhttp还是蛮好用的,但是我不会对其进行封装,于是乎就百度了一发,看了下别人的博客,发现有位大佬写的真的好用,就把复制过来,以备以后使用。

大佬博客链接在此:

http://blog.csdn.net/qq_30379689/article/details/52998057

下面是代码:

public class HttpUtil {
    private static OkHttpClient client = null;

    private HttpUtil() {}

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (HttpUtil.class) {
                if (client == null)
                    client = new OkHttpClient();
            }
        }
        return client;
    }
    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void doPost(String url, Map mapParams, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    /**
     * Post请求发送JSON数据
     *
     * @param url
     * @param jsonParams
     * @param callback
     */
    public static void doPost(String url, String jsonParams, Callback callback) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
}

你可能感兴趣的:(android)