package com.bawei.day24.utils;
import android.util.Log;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
lic class OkHttpUtils {
//单例模式
private static OkHttpUtils okHttpUtils;
private OkHttpUtils(){
}
public static OkHttpUtils getInstance(){
if (okHttpUtils==null){
//同步锁
synchronized (OkHttpUtils.class){
if (okHttpUtils==null){
okHttpUtils = new OkHttpUtils();
}
}
}
return okHttpUtils;
}
//封装OkHttp请求
private static OkHttpClient okHttpClient =null;
private static synchronized OkHttpClient getOkHttpClient(){
if (okHttpClient==null){
//拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("lan",message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.build();
return chain.proceed(request);
}
})
.build();
}
return okHttpClient;
}
//doGet方法
public void doGet(String url, Callback callback){
OkHttpClient okHttpClient = getOkHttpClient();
//请求方式
Request request = new Request.Builder().url(url).build();
//执行
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
//doPost方法
public void doPost(String url, Map<String,String>map,Callback callback){
OkHttpClient okHttpClient = getOkHttpClient();
//请求体
FormBody.Builder formBody = new FormBody.Builder();
//取值
for (String ma:map.keySet()) {
formBody.add(ma,map.get(ma));
}
//请求方式
Request request = new Request.Builder().url(url)
.build();
//执行
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
}