拦截器的运用

来源:互联网 发布:小丽和小云在计算 编辑:程序博客网 时间:2024/06/05 23:02
红色字体为添加拦截器部分
OkHttpClient okhttp = new OkHttpClient.Builder()        .connectTimeout(10, TimeUnit.SECONDS)        .readTimeout(20, TimeUnit.SECONDS)        .addInterceptor(new HttpInterceptor())        .build();
下面为封装的ok:
public class HttpUtils<F> {    private ISecondView netDataCallback;    private Handler mhand=new Handler();    public <T> void getdata(String url, final ISecondView netDataCallback, final Class<T> tclass) {       // OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new HttpInterceptor()).build();        //初始化一个 OkHttpClient 并且设置连接和读取超时时间        OkHttpClient okhttp = new OkHttpClient.Builder()                .connectTimeout(10, TimeUnit.SECONDS)                .readTimeout(20, TimeUnit.SECONDS)                .addInterceptor(new HttpInterceptor())                .build();        //构造一个Request对象        Request request = new Request.Builder().url(url).build();        //通过request的对象去构造得到一个Call对象        Call call = okhttp.newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {              //  netDataCallback.faild(499,e.getMessage());            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String string = response.body().string();                netDataCallback.onSuccess(string);                            }        });    }
创建接口:
public interface ISecondView{    void onSuccess(String t);    void onError(int errCode, String errMessage);}

用时方法:
实现接口
implements ISecondView
在主方法里面写:
  HttpUtils<Musiclist2> utils = new HttpUtils<>();utils.getdata(URL,this,Musiclist2.class );
重写接口内方法:
得到数据