【发布时间】:2019-05-13 17:34:00
【问题描述】:
我开始学习 Retrofit 和 Rxjava2 的一些用法。我正在尝试从https://restcountries.eu/rest/v2/all/ 获取所有国家/地区,但我无法理解它。我希望从上面的 url 中获取所有信息,并像 https://restcountries.eu/rest/v2/name/usa 一样单调。你能帮我实现吗?
public interface ApiService {
@GET("country/{country_id}")
Single<Country> getCountryData(@Path("name") String name);
@GET("country/{country_id}")
Call<Country> getAllCountries(@Path("array") String name);
}
国家:
public class Country {
@Expose
@SerializedName("name")
private Integer name;
@Expose
@SerializedName("capital")
private String capital;
@Expose
@SerializedName("population")
private int population;
}
主类:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get all
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://restcountries.eu/rest/v2/all/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
apiService.getAllCountries("array").subscribe(new SingleObserver<Country>() {
@Override
public void onSubscribe(Disposable d) {
// we'll come back to this in a moment
}
@Override
public void onSuccess(Country country) {
// data is ready and we can update the UI
Log.d("DTAG",country.getName());
}
@Override
public void onError(Throwable e) {
// oops, we best show some error message
}
});;
//Gat Single
Retrofit retrofitSingle = new Retrofit.Builder()
.baseUrl("https://restcountries.eu/rest/v2/all/USA")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
ApiService apiServiceSingle = retrofitSingle.create(ApiService.class);
apiServiceSingle.getAllCountries("array").subscribe(new SingleObserver<Country>() {
@Override
public void onSubscribe(Disposable d) {
// we'll come back to this in a moment
}
@Override
public void onSuccess(Country country) {
// data is ready and we can update the UI
Log.d("DTAG","");
}
@Override
public void onError(Throwable e) {
// oops, we best show some error message
}
});;
}
【问题讨论】: