使用不同的基本 url 配置 Retrofit

ara*_*aju 6 android okhttp retrofit2

我正在将 Android 应用程序切换为使用 Retrofit2 而不是 Volley。最初,我有一个单例 Retrofit 实例,我将用它来创建 Retrofit 服务对象。但应用程序需要与具有不同 url 基 url 的服务进行通信。我试图找出在 Retrofit 中切换基本 url 的最佳方法是什么。我已阅读以下解决方案:

  1. 我读过建议在拦截器级别切换基本 url 的线程。这似乎是一个 hacky 解决方案,在网络层切换基本 url。
  2. 还可以选择使用多个 Retrofit 实例来处理不同的 url。我不太喜欢这个,因为它最终可能会创建大量的 Retrofit 实例。

在我的应用程序中,90% 的调用都是对相同的基本 url 进行的。其他 10% 有 4-5 个不同的网址。现在我觉得最好只使用 OkHttp 来使用这些异常值调用。

关于这个问题有什么好的解决方案吗?

Pal*_*dro 6

我已经解决了,方法如下:

这是我的改造实例:

    val retrofit = Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl("http://baseurl....")
            .client(client)
            .build()
Run Code Online (Sandbox Code Playgroud)

当我下载数据时,我只需这样更改网址:

@GET
fun downloadData(@Url url: String): Observable<Response<ResponseBody>>
Run Code Online (Sandbox Code Playgroud)


Bis*_*Abd 1

public class RetrofitService {  
public static String apiBaseUrl = "http://myurl";
private static Retrofit retrofit;

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient =
        new OkHttpClient.Builder();



public static void changeApiBaseUrl(String newApiUrl) {
    apiBaseUrl = newApiUrl;

    builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(apiBaseUrl);
}

public static <S> S createRetrofitService(Class<S> serviceClas) {

    retrofit = builder.build();
    return retrofit.create(serviceClass);;
  }
Run Code Online (Sandbox Code Playgroud)

你的第一个 API 调用是

MyFirstApi api1=RetrofitService.createRetrofitService(MyFirstApi.class);
//..............
Run Code Online (Sandbox Code Playgroud)

您的第二个 API 调用将是。

RetrofitService.changeApiBaseUrl("your new url");
MySecondApi api2=RetrofitService.createRetrofitService(MySecondApi.class); 
Run Code Online (Sandbox Code Playgroud)