我创建了名为AppRetroServiceModule的应用程序模块以提供改进。

@Module(includes = NetworkModule.class)
public class AppRetroServiceModule {

    @Provides
    @AppScope
    public RetroService retroService(Retrofit retrofit) {
        return retrofit.create(RetroService.class);
    }

    @Provides
    @AppScope
    public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) {
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient)
                .baseUrl("http://webservise/Srv1.svc/json/")
                .build();
    }
}


如您所见,baseUrl是硬编码和固定的。在应用程序组件中,当应用程序组件是其他组件的依赖项时,我创建了getter来进行改造和其他提供程序:

@AppScope
@Component(modules = {NetworkModule.class, AppRetroServiceModule.class})
public interface IApplicationComponent {
    RetroService getRetroService();

    Gson getGsonBuilder();

    Context getAppContext();
}


我在应用程序类中初始化了匕首:

public class App extends Application {
    private IApplicationComponent component;
    ...
    @Override
    public void onCreate() {
        super.onCreate();

        Timber.plant(new Timber.DebugTree());
        component = DaggerIApplicationComponent.builder()
                .networkModule(new NetworkModule(this))
                .build();

    }...

    public IApplicationComponent getAppComponent() {
        return component;
    }
}


现在在主要活动中,我需要使用其他baseurl从服务器获取数据:

public class MainActivity extends AppCompatActivity implements IMain.IMainView {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_m);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        DaggerIMainComponent.builder()
                .iApplicationComponent(((App) getApplication()).getAppComponent())
                .build()
                .inject(this);
    ...


由于改造是在启动应用程序时初始化的,因此当我需要从其他活动或片段中的服务器中获取数据时,如何随时更改改造baseurl
有时我需要连接到许多服务器,并从这些服务器中获取数据并用于一项活动,然后我需要更改每一个需要的baseurl

最佳答案

如果您的基本网址是动态的,则可以使用@Url。这将帮助您将动态基本URL传递给您的请求。

public interface RetrofitClient {

    // Simple call with dynamic url
    @GET
    public Call<YouModelClass> doSomeRequest(@Url String url);

    // Call with dynamic url and request parameter
    @GET
    public Call<YouModelClass> doSomeRequest(@Url String url, @Query("id") String id);

    // Call with dynamic url and more request parameters
    @GET
    public Call<YouModelClass> doSomeRequest(@Url String url, @Query("id") String id, @Query("key") String key, @Query("part") String part);
}


调用代码将是

RetrofitClient service = retrofit.create(RetrofitClient.class);
Call<YouModelClass> call = service.doSomeRequest("your_dynamic_url_with_base_url");
// and so on


Retrofit 2 — How to Use Dynamic Urls for Requests阅读更多

10-07 19:26
查看更多