package com.example.lxxx.HTTP;
import android.animation.ObjectAnimator;
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.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 OkHttp {
private static volatile OkHttp instance;
private OkHttpClient client;
private Handler handler=new Handler();
//创建拦截器
private Interceptor getAppInterceptor(){
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e("+++","拦截前");
Response proceed = chain.proceed(request);
Log.e("+++","拦截后");
return proceed;
}
};
return interceptor;
}
//添加拦截器
private OkHttp(){
File file=new File(Environment.getExternalStorageDirectory()+"childe");
new OkHttpClient().newBuilder()
.connectTimeout(3000,TimeUnit.SECONDS)
.readTimeout(3000,TimeUnit.SECONDS)
.addInterceptor(getAppInterceptor())
.cache(new Cache(file,1024*10)).build();
}
//添加单例
public static OkHttp getInstance(){
if (instance==null){
synchronized (OkHttp.class){
if (instance==null){
instance=new OkHttp();
}
}
}
return instance;
}
//封装
public void Doget(String url, final Class clazz, final NetCallBack netCallBack){
final Request request=new Request.Builder().get().url(url).build();
//创建Call对象
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException 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() {
netCallBack.Succee(o);
}
});
}
});
}
//封装DoPosy
public void DoPost(String url, final Class clazz,String name,String pwd ,final NetCallBack netCallBack){
client=new OkHttpClient();
FormBody formBody=new FormBody.Builder()
.add("phone",name)
.add("pwd",pwd)
.build();
Request request=new Request.Builder().post(formBody).url(url).build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException 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() {
netCallBack.Succee(o);
}
});
}
});
}
public interface NetCallBack{
public void Succee(Object succ);
public void Error(Exception e);
}
}
OkHttp
最新推荐文章于 2021-04-07 10:22:47 发布