Change retrofit baseurl that initialized in application class with dagger2












1















I created Application module called AppRetroServiceModule to provide retrofit.



@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();
}
}


As you can see baseUrl is hardcoded and fixed. In application component I created getter to get retrofit and other provider, when application component is dependency for other component :



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

Gson getGsonBuilder();

Context getAppContext();
}


I initialized dagger in application class:



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;
}
}


Now in main activity i need to use other baseurl to fetching data from server :



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);
...


Because retrofit is initialized when application is started, how can i change anytime retrofit baseurl when i need to fetch data from servers in other activity or fragment ?
Sometimes i need to connect to number of servers and fetch data from these server and use in one activity then i need to change baseurl every i needed.










share|improve this question























  • You can use approach described here

    – ConstOrVar
    Nov 21 '18 at 6:49
















1















I created Application module called AppRetroServiceModule to provide retrofit.



@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();
}
}


As you can see baseUrl is hardcoded and fixed. In application component I created getter to get retrofit and other provider, when application component is dependency for other component :



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

Gson getGsonBuilder();

Context getAppContext();
}


I initialized dagger in application class:



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;
}
}


Now in main activity i need to use other baseurl to fetching data from server :



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);
...


Because retrofit is initialized when application is started, how can i change anytime retrofit baseurl when i need to fetch data from servers in other activity or fragment ?
Sometimes i need to connect to number of servers and fetch data from these server and use in one activity then i need to change baseurl every i needed.










share|improve this question























  • You can use approach described here

    – ConstOrVar
    Nov 21 '18 at 6:49














1












1








1








I created Application module called AppRetroServiceModule to provide retrofit.



@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();
}
}


As you can see baseUrl is hardcoded and fixed. In application component I created getter to get retrofit and other provider, when application component is dependency for other component :



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

Gson getGsonBuilder();

Context getAppContext();
}


I initialized dagger in application class:



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;
}
}


Now in main activity i need to use other baseurl to fetching data from server :



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);
...


Because retrofit is initialized when application is started, how can i change anytime retrofit baseurl when i need to fetch data from servers in other activity or fragment ?
Sometimes i need to connect to number of servers and fetch data from these server and use in one activity then i need to change baseurl every i needed.










share|improve this question














I created Application module called AppRetroServiceModule to provide retrofit.



@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();
}
}


As you can see baseUrl is hardcoded and fixed. In application component I created getter to get retrofit and other provider, when application component is dependency for other component :



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

Gson getGsonBuilder();

Context getAppContext();
}


I initialized dagger in application class:



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;
}
}


Now in main activity i need to use other baseurl to fetching data from server :



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);
...


Because retrofit is initialized when application is started, how can i change anytime retrofit baseurl when i need to fetch data from servers in other activity or fragment ?
Sometimes i need to connect to number of servers and fetch data from these server and use in one activity then i need to change baseurl every i needed.







android retrofit2 dagger-2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 4:23









sayres kabirsayres kabir

476215




476215













  • You can use approach described here

    – ConstOrVar
    Nov 21 '18 at 6:49



















  • You can use approach described here

    – ConstOrVar
    Nov 21 '18 at 6:49

















You can use approach described here

– ConstOrVar
Nov 21 '18 at 6:49





You can use approach described here

– ConstOrVar
Nov 21 '18 at 6:49












1 Answer
1






active

oldest

votes


















1














If your base url is dynamic then you can use @Url. This will help you to pass dynamic base url to your requests.



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);
}


And calling code would be



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


Read more at Retrofit 2 — How to Use Dynamic Urls for Requests






share|improve this answer


























  • If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 4:59











  • @sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:01











  • So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:04











  • Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 8:36






  • 1





    @sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

    – Pankaj Kumar
    Nov 21 '18 at 8:45











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405224%2fchange-retrofit-baseurl-that-initialized-in-application-class-with-dagger2%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














If your base url is dynamic then you can use @Url. This will help you to pass dynamic base url to your requests.



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);
}


And calling code would be



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


Read more at Retrofit 2 — How to Use Dynamic Urls for Requests






share|improve this answer


























  • If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 4:59











  • @sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:01











  • So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:04











  • Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 8:36






  • 1





    @sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

    – Pankaj Kumar
    Nov 21 '18 at 8:45
















1














If your base url is dynamic then you can use @Url. This will help you to pass dynamic base url to your requests.



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);
}


And calling code would be



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


Read more at Retrofit 2 — How to Use Dynamic Urls for Requests






share|improve this answer


























  • If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 4:59











  • @sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:01











  • So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:04











  • Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 8:36






  • 1





    @sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

    – Pankaj Kumar
    Nov 21 '18 at 8:45














1












1








1







If your base url is dynamic then you can use @Url. This will help you to pass dynamic base url to your requests.



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);
}


And calling code would be



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


Read more at Retrofit 2 — How to Use Dynamic Urls for Requests






share|improve this answer















If your base url is dynamic then you can use @Url. This will help you to pass dynamic base url to your requests.



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);
}


And calling code would be



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


Read more at Retrofit 2 — How to Use Dynamic Urls for Requests







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 5:02

























answered Nov 21 '18 at 4:55









Pankaj KumarPankaj Kumar

64.5k22132160




64.5k22132160













  • If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 4:59











  • @sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:01











  • So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:04











  • Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 8:36






  • 1





    @sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

    – Pankaj Kumar
    Nov 21 '18 at 8:45



















  • If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 4:59











  • @sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:01











  • So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

    – Pankaj Kumar
    Nov 21 '18 at 5:04











  • Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

    – sayres kabir
    Nov 21 '18 at 8:36






  • 1





    @sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

    – Pankaj Kumar
    Nov 21 '18 at 8:45

















If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

– sayres kabir
Nov 21 '18 at 4:59





If i use @Url, what will happen to .baseUrl("http://webservise/Srv1.svc/json/") that i have created when start application?@Pankaj Kumar

– sayres kabir
Nov 21 '18 at 4:59













@sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

– Pankaj Kumar
Nov 21 '18 at 5:01





@sayreskabir Nothing will happen with that part. It will be ignored for these methods and when you will call any service without using @url, this base url will be used.

– Pankaj Kumar
Nov 21 '18 at 5:01













So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

– Pankaj Kumar
Nov 21 '18 at 5:04





So does not matter if you set base url or not, if you use @url then this base url will be ignored and the url which you pass as the value of @url will be used.

– Pankaj Kumar
Nov 21 '18 at 5:04













Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

– sayres kabir
Nov 21 '18 at 8:36





Dude , I am using post method so i got error java.lang.IllegalArgumentException: @Url cannot be used with @POST URL (parameter #1) . seems i can not use in post method. What is other suggestion@Pankaj Kumar

– sayres kabir
Nov 21 '18 at 8:36




1




1





@sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

– Pankaj Kumar
Nov 21 '18 at 8:45





@sayreskabir It works with POST also. You current code is wrong. Use it like @POST Call<ResponseBody> getCiFloor(@Url String url, @Body JsonObject jsonBody);

– Pankaj Kumar
Nov 21 '18 at 8:45




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405224%2fchange-retrofit-baseurl-that-initialized-in-application-class-with-dagger2%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Guess what letter conforming each word

Port of Spain

Run scheduled task as local user group (not BUILTIN)