現(xiàn)在網(wǎng)絡(luò)請求很流行使用他們的結(jié)合
首先添加依賴:
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
創(chuàng)建網(wǎng)絡(luò)返回數(shù)據(jù)的對象,如ResponseInfo
class ResponseInfo{
}
創(chuàng)建接口(我寫的比較簡單)
public interface Test2Api {
@GET("myday05/a.json")
Observable<ResponseInfo> getTest();
}
網(wǎng)絡(luò)請求代碼
retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://192.168.0.190:8989/")
.build();
// 創(chuàng)建網(wǎng)絡(luò)請求接口的實(shí)例
Test2Api test2Api = retrofit.create(Test2Api.class);
observable = test2Api.getTest();
subscribe = observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseInfo>() {
@Override
public void onCompleted() {
Log.e("www", "onCompleted ");
}
@Override
public void onError(Throwable e) {
Log.e("www", "onError = " + e.getMessage());
}
@Override
public void onNext(ResponseInfo responseInfo) {
Log.e("www", "onNext = " + responseInfo.toString());
}
});