package com.example.skr.week2_20190105.utils;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttp3 {
private static final String TAG = "HttpUtils";
private static volatile OkHttp3 instance;
public Handler handler = new Handler();
private final OkHttpClient client;
private Interceptor getAppInterceptor(){
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e("++++++","拦截前");
Response response = chain.proceed(request);
Log.e("++++++","拦截后");
//请求之后
return response;
}
};
return interceptor;
}
private OkHttp3(){
File file = new File(Environment.getExternalStorageDirectory(),"cache11");
client = new OkHttpClient().newBuilder()
.readTimeout(3000, TimeUnit.SECONDS)
.connectTimeout(3000, TimeUnit.SECONDS)
.addInterceptor(getAppInterceptor())
.cache(new Cache(file, 10 * 1024))
.build();
}
//单例OkHttp
public static OkHttp3 getInstance(){
if (instance == null){
synchronized (OkHttp3.class){
if (null == instance){
instance = new OkHttp3();
}
}
}
return instance;
}
public void doGet(String url,final NetCallBack netCallBack){
final Request request = new Request.Builder()
.get()
.url(url)
.build();
//创建一个call对象
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.onFailure(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.onSuccess(result);
}
});
}
});
}
public void doPost(String url, Map<String,String> parms, final NetCallBack netCallBack){
FormBody.Builder body = new FormBody.Builder();
for (String key:parms.keySet()){
body.add(key,parms.get(key));
}
Request request = new Request.Builder()
.url(url)
.post(body.build())
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailure(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.onSuccess(result);
}
});
}
});
}
public interface NetCallBack {
void onSuccess(String data);
void onFailure(Exception e);
}
}