OkHttpClient网络请求

import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by user on 2017/11/8.
 * 网络请求工具类
 * 1.先导入OkHttpClient的jar包,然后导入com.squareup.okhttp3:logging-interceptor拦截器的包
 * 2.完善HttpUtil的工具类(1).getHttpUtil双层判断
 *                      (2).HttpUtil,创建OkHttpClient
 */

public class HttpUtil {
    private static HttpUtil httpUtil;
    private final OkHttpClient client;

    private HttpUtil() {
        //创建拦截器
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //创建OkHttp
        client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();
    }

    public static HttpUtil getHttpUtil() {
        if (httpUtil == null) {
            synchronized (HttpUtil.class) {
                if (httpUtil == null) {
                    httpUtil = new HttpUtil();
                }
            }
        }
        return httpUtil;
    }

    /**
     * GET请求
     *
     * @param url      请求地址
     * @param callback 回调
     */
    public void doGet(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * post请求
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callback 回调
     */
    public void doPost(String url, Map params, Callback callback) {
        //这里可以加网络判断

        /*//判断参数
        if (params == null || params.size() ==0){
            //运行时异常
            throw new RuntimeException("params is null!!!");
        }*/
        //创建Request
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry entry : params.entrySet()) {
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        client.newCall(request).enqueue(callback);
    }
}
 
  
//OnNetListener
public interface OnNetListener<T> {
    //成功回调
    public void onSuccess(T t);

    //失败回调
    public void onFailure(Exception e);
}

你可能感兴趣的:(OkHttpClient网络请求)