api 'com.squareup.retrofit2:retrofit:2.5.0' //Retrofit2所須要的包
api 'com.squareup.retrofit2:converter-gson:2.5.0' //ConverterFactory的Gson依賴包,也可指定其餘解析方式
api 'com.squareup.retrofit2:adapter-rxjava2:2.5.0' //結合使用的rxjava2的依賴包
rxjava2的依賴包
api 'io.reactivex.rxjava2:rxandroid:2.1.0'
api 'io.reactivex.rxjava2:rxjava:2.2.6'
okHttp的依賴包
api 'com.squareup.okhttp3:okhttp:3.12.0'
Gson的依賴包
api 'com.google.code.gson:gson:2.8.5'
複製代碼
建立請求方法java
public interface RequestService {
@GET("users/{user}/repos")
Observable<RequestResult> getDatas(@Path("user") String user, @Query("key") String value);
}
複製代碼
建立Retrofit實例react
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("") //網絡請求URL相對固定的地址
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //與rxjava聯合使用
.addConverterFactory(GsonConverterFactory.create()) //gson解析返回值
.client(okHttpClient) //使用OkHttp請求
.build();
複製代碼
建立請求Apiandroid
RequestService requestService = retrofit.create(RequestService.class);
複製代碼
發起請求api
Observable<RequestResult> observable = requestService.getDatas(user, value);
observable.subscribe(Subscriber)......複製代碼