当前位置: 首页 > 工具软件 > OkHttps > 使用案例 >

OkHttps的get post封装

卓嘉良
2023-12-01

1.

public class OkHttps {
private static OkHttps instance;
private Handler handler=new Handler(Looper.getMainLooper());
    private OkHttpClient okHttpClient;
//创建单例模式
        public static OkHttps getInstance(){
            if(instance==null){
                synchronized (OkHttps.class){
                    instance=new OkHttps();
}
            }
                    return instance;
                    }
    //创建拦截器
    private OkHttps(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
      loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
              okHttpClient = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .addNetworkInterceptor(loggingInterceptor)
                .build();
    }
//创建doget方法
    public void doget(String url, final ICallback iCallback, final sBean bean){

        //获取请求
        Request request = new Request.Builder()
                .url(url)
                .get()
                .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.onFaild(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String s = response.body().string();
                Gson gson = new Gson();
                final sBean bb = gson.fromJson(s, sBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        iCallback.onSuccess(bb);
                    }
                });
            }
        });

    }
//创建接口
    public interface ICallback{
        void onSuccess(Object object);
        void onFaild(Exception s);
}
}
 类似资料: