首先对他进行简单的介绍
Retrofit是Square开发的一个用于网络请求的开源库,内部封装了okhttp,并且和RxAndroid完美的兼容,使得Android的开发效率增加不少的同时也使代码变得清晰易读。
下面就是使用了
第一步添加依赖
compile 'io.reactivex:rxjava:1.1.3' compile 'io.reactivex:rxandroid:1.1.0' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:converter-scalars:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
第二步
使用上代码都有注释
//创建Retrofit Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_PATH).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); //通过动态代理得到网络接口对象 //http://service.meiyinkeqiu.com/service/ads/cptj //"http://service.meiyinkeqiu.com/service/" // retrofit.create(ApiServices); ApiService apiService = retrofit.create(ApiService.class); //得到Observable Observable<News> observable = apiService.getNoParams();//获取数据源 observable.subscribeOn(Schedulers.io())//IO线程做耗时操作 .observeOn(AndroidSchedulers.mainThread())//在主线程更新UI .subscribe(new Observer<News>() { //完成 @Override public void onCompleted() { Toast.makeText(MainActivity.this,"onCompleted",Toast.LENGTH_LONG).show(); Log.d("MainActivity", "onCompleted: "); } //异常 @Override public void onError(Throwable e) { Log.d("MainActivity", "onError: "+e.getMessage()); } // 加载中 @Override public void onNext(News news) { Log.d("MainActivity", "onNext: "); List<News.AdsBean> ads = news.getAds(); for (int i = 0; i < ads.size(); i++) { Log.i("xxx",ads.get(i).getGonggaoren()); mtv.setText(ads.get(i).getGonggaoren()); } } }); }以上使用了API类是
public class Api { public static final String BASE_PATH = "http://service.meiyinkeqiu.com"; public static final String BASE_URL = "https://api.github.com/"; public static final String HOME_URL="http://api.expoon.com/AppNews/getNewsList/";
service接口
public interface ApiService { /** * 结合Retrofit+RxJava * http://service.meiyinkeqiu.com/service/ads/cptj * @param * @return */ @GET("/service/ads/cptj") Observable<News> getNoParams(); /** * 结合RxJava * @param user * @return * https://api.github.com/users/forever */ @GET("users/{user}") Observable<User> getHasParams(@Path("user")String user); //第三个接口,,兼容json解析功能,,集成rxjava square retrofit //https://api.github.com/repos/square/retrofit/contributors @GET("repos/{square}/{retrofit}/contributors") Observable<List<Datas>> getHasParams2(@Path("square") String square, @Path("retrofit")String retrofit); @GET("type/1/p/1") Observable<Homes> getHomes(); } 以上就是基本的实现了以下添加拦截器
//创建okhttpclient,方便添加拦截器 LoggingInterceptor()是你自己的拦截器
OkHttpClient.Builder client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor());
要添加拦截器只需在retrofit的链式操作中加上.client(client)