public class MainActivity extends AppCompatActivity { @SuppressLint("CheckResult") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApiClient.retrofit().create(ApiStores.class).loadDataByRetrofitRxJava("101220602") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<MainModel>() { @Override public void onSubscribe(Disposable d) { Log.w ( "Output:", "connection" ); } @Override public void onNext(MainModel mainModel) { Log.w("输出:", "" + mainModel.getWeatherinfo().getCity()); Log.d("输出:", "observer thread is : " + Thread.currentThread().getName()); } @Override public void onError(Throwable e) { Toast.makeText (. MainActivity the this , "login failed" , Toast.LENGTH_SHORT) .Show (); } @Override public void onComplete() { Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); } }); } public interface ApiStores { //baseUrl String API_SERVER_URL = "http://www.weather.com.cn/"; // Load Weather @GET ( "ADAT / SK /} {cityId .html" ) Observable<MainModel> loadDataByRetrofitRxJava(@Path("cityId") String cityId); } }
Main method
public class ApiClient { public static Retrofit mRetrofit; public static Retrofit retrofit() { if (mRetrofit == null) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.readTimeout(5, TimeUnit.SECONDS); builder.connectTimeout(5, TimeUnit.SECONDS); if (BuildConfig.DEBUG) { // Log信息拦截器 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // Set Debug Log mode builder.addInterceptor (loggingInterceptor); } OkHttpClient okHttpClient = builder.build(); mRetrofit = new Retrofit.Builder() .baseUrl (MainActivity.ApiStores.API_SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build(); } return mRetrofit; } }
New Class
public class MainModel { public static WeatherinfoBean getWeatherinfo() { return new WeatherinfoBean(); } public static class WeatherinfoBean { private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } } }
implementation 'io.reactivex.rxjava2:rxjava:2.2.9' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' //retrofit implementation 'com.squareup.retrofit2:retrofit:2.6.0' // Gson converter implementation 'com.squareup.retrofit2:converter-gson:2.6.0' //RxJava2 Adapter implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0" //okhttp implementation 'com.squareup.okhttp3:okhttp:3.12.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
Copied directly dependent synchronization and to build.gride