public class OkHttp { private static OkHttpClient okHttpClient; private static volatile OkHttp instance; //拦截器 private Interceptor getAppInterceptor(){ Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //拦截前 Response proceed = chain.proceed(request); //拦截后 return proceed; } }; return interceptor; } //设置拦截器 private OkHttp(){ new OkHttpClient().newBuilder() .addInterceptor(getAppInterceptor()) .build(); } //单例 public static OkHttp getInstance(){ if (instance==null){ synchronized (OkHttp.class){ if (instance==null){ OkHttp okHttp = new OkHttp(); } } } return instance; } //get方法 private static void OkGet(String url,final Class clazz, final setdata setdata){ OkHttpClient okHttpClient = new OkHttpClient(); Request get = new Request.Builder().url(url).method("GET", null).build(); okHttpClient.newCall(get).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { setdata.getdata(response.body().string()); } }); } //post方法 private static void OkPost(String url,final Class clazz, String name,String pass,final setLogin setLogin){ okHttpClient = new OkHttpClient(); FormBody build = new FormBody.Builder() .add("phone", name) .add("pwd", pass) .build(); Request build1 = new Request.Builder().url(url).post(build).build(); okHttpClient.newCall(build1).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { setLogin.getlogindata(response.body().string()); } }); } //post方法接口 private interface setLogin{ void getlogindata(String logindata); } //get方法接口 private interface setdata{ void getdata(String data); }
Okhttp3
最新推荐文章于 2022-07-25 15:30:39 发布