private static volatile OkHttps instance;
private static Request request;
private static RequestBody builder;
private static OkHttpClient okHttpClient;
private static Interceptor getInterceptor(){
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;
};
//创建Get请求方法
private OkHttps() {
File file = new File(Environment.getExternalStorageDirectory(), "cache11");
okHttpClient = new OkHttpClient().newBuilder()
.readTimeout(3000, TimeUnit.SECONDS) //设置读取超时时间
.connectTimeout(3000, TimeUnit.SECONDS) //设置连接的超时时间
.addInterceptor(getInterceptor())//Application拦截器
.cache(new Cache(file, 10 * 1024))
.build();
}
//实现单利模式
//单例okhttp
//OkHttps
public static OkHttps getInstance() {
if (instance == null) {
synchronized (OkHttps.class) {
if (null == instance) {
instance = new OkHttps();
}
}
}
return instance;
}
public static void OkHttpget(String url, Callback callss){
//创建okHttpClient
okHttpClient = new OkHttpClient().newBuilder().
addInterceptor(getInterceptor()).build();
//创建request
request = new Request.Builder().url(url).method("GET",null).build();
//
okHttpClient.newCall(request).enqueue(callss);
}
//okhttp post请求
public static void OkHttpPost(String url,String name,String pswd ,Callback call){
okHttpClient = new OkHttpClient().
newBuilder().
addInterceptor(getInterceptor()).build();
builder = new FormBody.Builder()
.add("mobile",name)
.add("password",pswd)
.build();
//创建request
request = new Request
.Builder()
.url(url)
.post(builder)
.build();
okHttpClient.newCall(request).enqueue(call);
}