Rxjava+Retrofit

定義接口

public interface ApiService {
    /**
     * 獲取服務器時間
     * @return
     */
    @GET("serverTime.json")
    Observable<ServerTimeResBean> getServerTime();
}
//HttpManager 
public class HttpManager {
    private static final String BASE_URL = "https://XXX.com/";
    private static HttpManager INSANCE;
    private ApiService apiService;;

    public static HttpManager getInstance(){
        if(INSANCE == null){
            synchronized (HttpManager.class){
                if(INSANCE == null){
                    INSANCE= new HttpManager();
                }
            }
        }
        return INSANCE;
    }

    private HttpManager(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(new OkHttpClient.Builder()
                        .connectTimeout(15L, TimeUnit.SECONDS)//設置超時時間
                        .retryOnConnectionFailure(true)
                        .addInterceptor(new CommonInterceptor()).build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public ApiService getApiService(){
        return apiService;
    }
}

 

//攔截器,可以打印日誌,或者修改接口參數,加請求頭

public class CommonInterceptor  implements Interceptor {
    private static final String TAG = "CommonInterceptor";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request =  chain.request();
        //可以修改參數 ...

        Response response = chain.proceed(request);
        HttpUrl url = request.url();

        Charset charset;
        charset = Charset.forName("UTF-8");
        ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
        Reader jsonReader = new InputStreamReader(responseBody.byteStream(), charset);
        BufferedReader reader = new BufferedReader(jsonReader);
        StringBuilder sbJson = new StringBuilder();
        String line = reader.readLine();
        do {
            sbJson.append(line);
            line = reader.readLine();
        } while (line != null);
        //打印接口日誌
        Log.e(TAG, "method :" + request.method() + " ,url:"+ url +" ,response: " + sbJson);
        return response;
    }
}

//接口調用:

HttpManager.getInstance().getApiService().getServerTime()
        .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io()).subscribe(new Consumer<ServerTimeResBean>() {
    @Override
    public void accept(ServerTimeResBean serverTimeResBean) throws Exception {
        Toast.makeText(MainActivity.this, "get server time:" + gson.toJson(serverTimeResBean), Toast.LENGTH_SHORT).show();
    }
}, new Consumer<Throwable>() {
    @Override
    public void accept(Throwable throwable) throws Exception {
        Log.e(TAG, "error: -->>" + throwable.toString());
    }
});

 

引入庫:

   implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'

// 用Gson解析json的轉換器
    implementation 'com.google.code.gson:gson:2.8.5'

//rxjava2
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.5'

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章