public class Api { public static final String BASE_PATH = "http://service.meiyinkeqiu.com/service/"; public static final String BASE_URL = "https://api.github.com/";
}
public interface ApiService { /** * 結合Retrofit+RxJava * thtp://service.meiyinkeqiu.com/service/ads/cptj * @param * @return */ @GET("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); }
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getNoParams(); } private void getNoParams() { Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_PATH).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RxJava .build(); 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() {//完成 } @Override public void onError(Throwable e) {//失敗 Log.i("xxx", e.getMessage()); } @Override public void onNext(News news) {//消費事件 List<News.AdsBean> ads = news.getAds(); for (int i = 0; i < ads.size(); i++) { News.AdsBean adsBean = ads.get(i); String gonggaoren = adsBean.getGonggaoren(); Log.i("xxx", gonggaoren); } } }); } }
compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' compile 'com.squareup.retrofit2:retrofit:2.0.1' compile 'com.squareup.okio:okio:1.5.0' compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.retrofit2:converter-gson:2.0.1' compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'