是的,你可以。
你应该在你的 gradle 中添加这个依赖:
dependencies {
...
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.2.1'
...
}
清单中的权限:
<uses-permission android:name="android.permission.INTERNET" />
服务创建者可能是这样的:
public class RxServiceCreator {
private OkHttpClient.Builder httpClient;
private static final int DEFAULT_TIMEOUT = 30; //seconds
private Gson gson;
private RxJavaCallAdapterFactory rxAdapter;
private Retrofit.Builder builder;
private static RxServiceCreator mInstance = null;
private RxServiceCreator() {
httpClient = new OkHttpClient.Builder();
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
builder = new Retrofit.Builder()
.baseUrl("yourbaseurl")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(rxAdapter);
if (BuildConfig.REST_DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
httpClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
httpClient.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}
public static RxServiceCreator getInstance() {
if (mInstance == null) {
mInstance = new RxServiceCreator();
}
return mInstance;
}
public <RESTService> RESTService createService(Class<RESTService> service) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(service);
}
}
你的界面可能是这样的:
public interface UserAPI {
@GET("user/get_by_email")
Observable<Response<UserResponse>> getUserByEmail(@Query("email") String email);
}
最后进行 api 调用:
UserAPI userApi = RxServiceCreator.getInstance().createService(UserAPI.class);
userApi.getUserByEmail("user@example.com")
.observeOn(AndroidSchedulers.mainThread())
.subscribe(userResponse -> {
if (userResponse.isSuccessful()) {
Log.i(TAG, userResponse.toString());
} else {
Log.i(TAG, "Response Error!!!");
}
},
throwable -> {
Log.e(TAG, throwable.getMessage(), throwable);
});