RxJava2 + Retrofit2 完全指南 之 動態Url/Path/Parameter/Header
前言
因為有需求,才會有解決方案。本篇文章就是為了解決以下類似問題:
- 統一為所有介面加上一個引數,如
appType
或則version
- 統一為請求加上一個
header
- 請求
path
變更了,需要按照一定規則將path
進行替換
實現
實現思路也是比較簡單的,只需要自己實現一個 Interceptor
,然後加在其它 Interceptor
之前,具體程式碼如下:
/** * 自定義的攔截器 * 1. 實現baseUrl的動態替換 * 2. path的替換 * 3. 增加parameter * 3. 增加header */ final class HostSelectionInterceptor implements Interceptor { @Override public okhttp3.Response intercept(Chain chain) throws IOException { // 拿到請求 Request request = chain.request(); HttpUrl httpUrl = request.url(); HttpUrl.Builder newUrlBuilder = httpUrl.newBuilder(); // 替換host String host = httpUrl.host(); // 這裡是判斷 當然真實情況不會這麼簡單 if (httpUrl.host().equals("api.github.com")) { // 只是為了在demo中顯示訊息提示 sendMessage("\n\n替換url:www.baidu.com\n"); host = "www.baidu.com"; } // 重新設定新的host newUrlBuilder.host(host); // 替換path //List<String> pathSegments = httpUrl.pathSegments(); // 這裡是我已經知道了我是要移除第一個路徑,所以我直接就移除了 // 真實專案中,判斷條件更加複雜 newUrlBuilder.removePathSegment(0); // 將index的segment替換為傳入的值 //newUrlBuilder.setPathSegment(index,segment); // 新增引數 newUrlBuilder.addQueryParameter("version", "v1.3.1"); // 建立新的請求 request = request.newBuilder() .url(newUrlBuilder.build()) .header("NewHeader", "NewHeaderValue") .build(); // 只是為了在demo中顯示訊息提示 sendMessage("\n\n新請求地址和引數:" + request.url().toString() + "\n"); return chain.proceed(request); } }
使用:
retrofit = new Retrofit.Builder() .client(new OkHttpClient.Builder() .addInterceptor(getHttpLoggingInterceptor()) .addInterceptor(hostSelectionInterceptor)//加入自定義的攔截器 .build()) .baseUrl("https://api.github.com/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build();
演示:

演示