package com.example.gouwuche2.util;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class OKhttp {
private static volatile OKhttp mInstance;
private OkHttpClient mClient;
private Handler handler = new Handler(Looper.getMainLooper());
//单例
public static OKhttp getmInstance(){
if(mInstance==null)
{
synchronized (OKhttp.class)
{
mInstance = new OKhttp();
}
}
return mInstance;
}
//完成构造方法
private OKhttp(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
mClient = new OkHttpClient.Builder()
.connectTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
}
//post请求
public void getRequest(String url, Map<String,String> params, final Class clazz, final ICallBack iCallBack){
OkHttpClient okHttpClient = new OkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
for(Map.Entry<String,String> entry:params.entrySet())
{
builder.add(entry.getKey(),entry.getValue());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.error(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Gson gson = new Gson();
final Object o = gson.fromJson(string, clazz);
handler.post(new Runnable() {
@Override
public void run() {
iCallBack.success(o);
}
});
}
});
}
}