最近好幾個朋友問我,多Url怎麼處理,這裏咱們就說說這個。php
Retrofit2是支持全路徑的,好比說css
@GET("http://api.csslcloud.net/api/room/create")
Observable<String> createRoom(@Path("param") String param);
複製代碼
因此,項目中只有個別接口須要的話,徹底可使用配置全路徑這種方式。java
保留多個Retrofit
對象 在以前的代碼中,Retrofit
一直是單例的,這裏咱們能夠建立2個Retrofit
對象git
retrofit = new Retrofit.Builder()
.baseUrl(BASE_SERVER_URL)
.addConverterFactory(BaseConverterFactory.create())
//支持RxJava2
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
retrofit2 = new Retrofit.Builder()
.baseUrl(BASE_SERVER_URL2)
.addConverterFactory(BaseConverterFactory.create())
//支持RxJava2
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
apiServer = retrofit.create(ApiServer.class);
apiServer2 = retrofit2.create(ApiServer.class);
複製代碼
而後在使用時,區分github
/** * 獲取微分享列表 */
public void getShareList() {
...省略代碼...
ApiServer apiServer = ApiRetrofit2.getInstance().getApiService();
...省略代碼...
}
/** * 獲取微分享列表 */
public void getShareList2() {
...省略代碼...
ApiServer apiServer = ApiRetrofit2.getInstance().getApiService2();
...省略代碼...
}
複製代碼
固然這裏也就說說而已,估計沒人會這麼用...api
思路是,經過Okhttp
的攔截器,動態改變接口的地址,那攔截器裏如何知道每一個接口該使用哪一個主地址呢? 這裏可使用head
,請求時,添加固定的標誌head,而後在攔截器中判斷,完成替換。ide
如何實現post
首先,在ApiServer
中定義接口,添加head
ui
/** * 獲取分享列表 * * @return */
@FormUrlEncoded
@POST("module/index.php?")
@Headers({"url_mark:1"})
Observable<List<ShareModel>> getShareList2(@FieldMap Map<String, String> map);
/** * 獲取分享列表 * * @return */
@FormUrlEncoded
@POST("module/index.php?")
@Headers({"url_mark:2"})
Observable<List<ShareModel>> getShareList3(@FieldMap Map<String, String> map);
複製代碼
而後在Interceptor
判斷head
private Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e(TAG, "----------Request Start----------------");
Log.e(TAG, "| OldUrl=" + request.url().toString());
List<String> mark = request.headers("url_mark");
HttpUrl newUrl = null;
if (mark != null && mark.size() > 0) {
Log.e(TAG, "| Head=" + mark.get(0));
if (mark.get(0).equals("1")) {
newUrl = HttpUrl.parse("http://www.baidu.com/");
} else if (mark.get(0).equals("2")) {
newUrl = HttpUrl.parse("http://www.github.com/");
} else {
newUrl = request.url();
}
request = request.newBuilder().url(newUrl).build();
}
Log.e(TAG, "| NewUrl=" + request.url().toString());
long startTime = System.currentTimeMillis();
Response response = chain.proceed(request);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.e(TAG, "| " + request.toString());
Log.e(TAG, "| Response:" + content);
Log.e(TAG, "----------Request End:" + duration + "毫秒----------");
return response.newBuilder()
.body(ResponseBody.create(mediaType, content))
.build();
}
};
複製代碼
結果以下:
固然,這裏是寫死的判斷,實際開發中,多是提早知道或者接口返回具體哪些接口地址,能夠存放在Map中,這裏直接取值就好。
最後,獻上源碼 Github
RetrofitUrlManager
還提供了了更加豐富的替換規則,詳情能夠查看源碼。