Retrofit封装

来源:互联网 发布:怎么淘宝开通不了花呗 编辑:程序博客网 时间:2024/05/22 11:37
所需需依赖
compile 'com.squareup.retrofit2:retrofit:2.0.1'compile 'com.squareup.retrofit2:converter-gson:2.0.1'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'compile 'io.reactivex:rxandroid:1.1.0'compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'compile 'com.facebook.fresco:fresco:0.14.1'compile 'com.jcodecraeer:xrecyclerview:1.3.2'compile 'com.android.support:recyclerview-v7:21.0.+'compile 'com.squareup.okhttp3:okhttp:3.0.0'compile 'com.squareup.okio:okio:1.5.0'


public class RetrofitUtils {
    private static RetrofitUtils retrofitUtils;
    private RetrofitUtils(){

    }
    public static RetrofitUtils getInstance(){
        if(retrofitUtils==null){
            synchronized (RetrofitUtils.class){
                if(retrofitUtils==null){
                    retrofitUtils=new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }

    private static Retrofit retrofit;
   public static synchronized Retrofit getRetrofit(String url){
     /*   HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("xxx",message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
*/
LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor();

        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(500, TimeUnit.SECONDS)
                .readTimeout(500,TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .build();
        if(retrofit==null){
            retrofit=new Retrofit.Builder().baseUrl(url)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }
    public <T>T getApiService(String url,Class<T> cl){
        Retrofit retrofit = getRetrofit(url);//得到retrofit

        return retrofit.create(cl);//返回的就是网络接口对象

    }


}






/** * 网络拦截器 */public class LoggingInterceptor implements Interceptor {    private static final String UA = "User-Agent";    @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request()                .newBuilder()                .addHeader(UA, makeUA())                .build();        return chain.proceed(request);    }    private String makeUA() {        String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;        return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;    }}


public  interface ApiService {    /**     * @param     * @return     */    @GET("ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0")    Observable<bean> getNoParams();//    /**//     * 结合RxJava//     * @param user//     * @return//     * https://api.github.com/users/forever//     *///    @GET("users/{user}")//    Observable<bean>  getHasParams(@Path("user")String user);}



//调用
ApiService apiService = RetrofitUtils.getInstance().getApiService("http://tingapi.ting.baidu.com/v1/restserver/", ApiService.class);Observable<bean> params = apiService.getNoParams();params.subscribeOn(Schedulers.io())//指定IO做耗时操作        .observeOn(AndroidSchedulers.mainThread())//指定更新UI在主线程        .subscribe(new Observer<bean>() {            @Override            public void onCompleted() {//完成            }            @Override            public void onError(Throwable e) {//失败                Log.i("x", e.getMessage());            }            @Override            public void onNext(bean bean) {//消费事件                Log.i("xxx", bean+"");                List<bean.SongListBean> song_list =bean.getSong_list();                for (int i = 0; i < song_list.size(); i++) {                    bean.SongListBean songListBean = song_list.get(i);                    String language = songListBean.getLanguage();                    Log.i("xx", language);                }            }        });