Android OkHttp3封装

public class OkHttpUtil {
private static Gson mGson=new Gson();
public static final String MEDIA_TYPE="application/json;charset=utf-8";
private static final String METHOD_GET="GET";
private static final String METHOD_POST="POST";
private static OkHttpClient okHttpClient;

/*
* 私有化构造方法
* 使用单例模式
* */
public OkHttpUtil() {
}

public static void init(){
    //OkHttpClient.Builder 建造模式 把需要的一些请求要求添加给OkHttpClient
    OkHttpClient.Builder builder=new OkHttpClient.Builder();
    builder.readTimeout(3000,TimeUnit.MILLISECONDS);
    builder.writeTimeout(3000,TimeUnit.MILLISECONDS);
    builder.connectTimeout(3000,TimeUnit.MILLISECONDS);
    //OkHttpClient获得OkHttpClient.Builder建造完的OkHttpClient
    okHttpClient=builder.build();
}
//处理传给的参数 并指明方法
private static Request createRequest(String url,String method,BassRequest bassRequest){
    RequestBody requestBody=null;
    if (bassRequest!=null){
        //将bean类转换成JSON数据
        String bodyJson = mGson.toJson(bassRequest);
        //媒体类型 指定的结构
        MediaType JSON=MediaType.parse(MEDIA_TYPE);
        //requestBody不是从零中闪出来的 是create出来的
        requestBody=RequestBody.create(JSON,bodyJson);
    }
    //将request建造出来并且将URL传给它 给它指明要访问的URL地址
    Request.Builder builder=new Request.Builder().url(url);
    //创建一个空的Request  由switch处理并把request的建造出来 付给request
    Request request=null;
    switch (method){
        case METHOD_GET:
            request=builder.build();
            break;
        case METHOD_POST:
            request=builder.post(requestBody).build();
            break;
    }
    return request;
}
public static void enqueueGet(String url, Callback callback){
    Request request = createRequest(url,METHOD_GET,null);
    Call call = okHttpClient.newCall(request);
    call.enqueue(callback);
}
public static void enqueuePost(String url,BassRequest bassRequest,Callback callback){
    Request request = createRequest(url, METHOD_POST, bassRequest);
    Call call = okHttpClient.newCall(request);
    call.enqueue(callback);
}

}

你可能感兴趣的:(Android OkHttp3封装)