I have a scenario where I have to call an API with the same base URL, e.g. www.myAPI.com but with a different baseUrl.
I have an instance of Retrofit 2 which is built via a Builder:
return new Retrofit.Builder()
.baseUrl(FlavourConstants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
The FlavourConstants.BASE_URL looks like this:
public static final String BASE_URL = "http://myApi.development:5000/api/v1/";
For some WebRequests, I must call the same API but on others, I must call it from a completely different BaseUrl. How do I change the Retrofit instance to therefore point to a different URL during runtime?
The Retrofit instance doesn't have a .setBaseUrl or setter or anything similar as it's built via a Builder.
Any ideas?
Lucky for you Retrofit have a simple solution for that:
public interface UserManager {
#GET
public Call<ResponseBody> userName(#Url String url);
}
The url String should specify the full Url you wish to use.
Retrofit 2.4, MAY 2019
Two simple solution for this hassle are:
Hardcode the new URL, while leaving the base URL as it is:
#GET("http://example.com/api/")
Call<JSONObject> callMethodName();
Pass the new URL as an argument, while leaving the base URL as it is:
#GET
Call<JSONObject> callMethodName(#Url String url);
N.B: These methods work for GET or POST. However, this solution is only efficient if you just need to use an exception of one or two different URLs than your base URL. Otherwise, things can get a little messy in terms of code neatness.
If your project demands fully dynamically generated base URLs then you can start reading this.
Also there is a such hack in Kotlin while defining base url
e.g.
#FormUrlEncoded
#Headers("Accept: application/json")
#POST
suspend fun login(
baseUrl: String,
#Field("login") login: String,
#Field("password") password: String
#Url url: String = "$baseUrl/auth"
): ResponseAuth
It's not working. Throws:
java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1)
The only way is suggested by Jake Wharton https://github.com/square/retrofit/issues/2161#issuecomment-274204152
Retrofit.Builder()
.baseUrl("https://localhost/")
.create(ServerApi::class.java)
class DomainInterceptor : Interceptor {
#Throws(Exception::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
return chain.proceed(
request.newBuilder()
.url(
request.url.toString()
.replace("localhost", "yourdomain.com:443")
.toHttpUrlOrNull() ?: request.url
)
// OR
//.url(HttpUrl.parse(request.url().toString().replace("localhost", "yourdomain.com:443")) ?: request.url())
.build()
)
}
}
The easiest (but not the most performant) way to change the Retrofit2 base URL at runtime is to rebuild the retrofit instance with the new url:
private Retrofit retrofitInstance = Retrofit.Builder().baseUrl(FlavourConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build();
public void setNewBaseUrl(String url) {
retrofitInstance = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient).build();
}
...
retrofitInstance.create(ApiService.class);
Alternatively, if you are using OkHttp with Retrofit, you can add an OkHttp interceptor like this one when building your OkHttp client:
HostSelectionInterceptor hostInterceptor = new HostSelectionInterceptor();
hostInterceptor.setHost(newBaseUrl);
return new OkHttpClient.Builder()
.addInterceptor(hostInterceptor)
.build();
I just used the below function when i faced this problem. but i was on hurry and i believe that i have to use another and i was using "retrofit2:retrofit:2.0.2"
public static Retrofit getClient(String baseURL) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
} else {
if (!retrofit.baseUrl().equals(baseURL)) {
retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
return retrofit;
}
[Update]
I have found this link that explain the #Url that can be sent as a parameter and i believe it is more professional than my old solution.
Please find below the scenario:
interface APIService{
#POST
Call<AuthenticationResponse> login(#Url String loginUrl,[other parameters])
}
And below is the method in the class that provide the retrofit object
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://baseurl.com") // example url
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
Then you can call the method as below:
APIInterface apiInterface = ApiClient.getClient2().create(ApiInterface.class);
apiInterface.login("http://tempURL.com").enqueue(......);
You should use interceptor like this:
class HostSelectionInterceptor: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
apiHost?.let { host ->
val request = chain.request()
val newUrl = request.url.newBuilder().host(host).build()
val newRequest = request.newBuilder().url(newUrl).build()
return chain.proceed(newRequest)
}
throw IOException("Unknown Server")
}
}
You just need to change at runtime the apiHost variable (var apiHost = "example.com"). Then add this interceptor to OkHttpClient builder:
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(HostSelectionInterceptor())
.build()
Ok , if I dont remember wrong the docs of Retrofit says you can point to another URL if you just simply add in your interface servicse the full url of the ws, that is different fomr the BASE_URL in Retrofit Builder. One example...
public interface UserManager {
#GET("put here ur entire url of the service")
public Call<ResponseBody> getSomeStuff();
}
A solution is to have two distinct instance of retrofit, one for your FLAVOURED base URL and another for the other base URL.
So just define two functions :
public Retrofit getFlavouredInstance() {
return new Retrofit.Builder().baseUrl(FlavourConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build();
}
public Retrofit getOtherBaseUrl() {
return Retrofit.Builder().baseUrl(OTHER_BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).client(okHttpClient).build();
}
and after you just have to use the right one.
Please try the following code:
private void modify(String url) throws Exception {
Class mClass = retrofit.getClass();
Field privateField = mClass.getDeclaredField("baseUrl");
if (privateField != null) {
privateField.setAccessible(true);
System.out.println("Before Modify:MSG = " + retrofit.baseUrl().url().getHost());
privateField.set(retrofit, HttpUrl.parse(url));
System.out.println("After Modify:MSG = " + retrofit.baseUrl().url().getHost());
}
}
You can regenerate the DaggerAppComponent after changing your apiUrl it will generate a new instance of providerRetrofit with the new url
DaggerAppComponent.builder() .application(this) .build() Log.init( LogConfiguration .Builder() .tag("...") .logLevel(LogLevel.NONE) .build() )
I found something strange when I add interceptor like this:
public ApiDefinition getService() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
System.out.println("into interceptor");
Request request = chain.request();
return chain.proceed(request);
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiDefinition.class);
}
Then when I do call a network, nothing print just like the interceptor did't work.
Observable observable = apiDefinition.getResponse();
observable.subscribe(....)
I am confused, was there anything wrong?
apiDefinition.getResponse(); you forgetting to subscribe api call. Just getting observable, but not observing it.
apiDefinition
.getResponse()
.subscribe(.......);
if you want to intercept Network request call and print them in logcat
you can do so by adding an HttpLoggingInterceptor like that:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
Sorry guys, i make some mistakes when i user dagger2 to inject ApiDefinition, so this is solved.
Using android retrofit, I'm having problems referring to my url.
Either of these are ok to use:
http://www.example.com/foo.asmx/dostuf
Or
http://www.example.com/foo.ashx?r=dostuff
The examples I've seen indicate:
http://www.example.com/post
What file is that processing?
So, how to I implement my url?
Thanks
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("Your Url")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
I've got it.
Here it is to help out others...
The BASE url goes here:
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.example.com/").build();
The ENDPOINT url goes here:
public interface retrofit_post1 {
#POST("example.ashx?r=dostuff")
Call<ResponseBody> update(#Body RequestBody requestBody);
}
I am learning to use retrofit, to consume Webservices, I have no problems in executing the #GET, #POST methods but now I have to execute a service where the token is sent, I really do not know how to do it, but I use POSTMAN where this field token I send from Headers in the Authorization key. I have seen other examples where OkHttpClient is used but I can not think of how to implement it.
So I execute my service with retrofit, to this same one the token in the head should be sent to him.
#GET(Constants.Retrofit.SURE_DO_YOU_LIKE_PRODUCTS)
Call<List<RelatedProducts>> getProductSureDoYouLike();
and this is my service in POSTMAN.
Like this:
#GET(Constants.Retrofit.SURE_DO_YOU_LIKE_PRODUCTS)
Call<List<RelatedProducts>> getProductSureDoYouLike(#Header("Content-Type") String contentType, #Header("Authorization") String auth);
If all requests require a Content-Type you could modify your Retrofit builder to include the header on every request:
OkHttpClient client;// = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.addInterceptor(chain -> {
Request request = chain.request().newBuilder()
//Add this to include header in every request
.addHeader("Content-Type", "application/json").build();
return chain.proceed(request);
}).build();
client = builder.build();
retrofit = new Retrofit.Builder()
.baseUrl(NetworkConstants.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
Then your request would be:
#GET(Constants.Retrofit.SURE_DO_YOU_LIKE_PRODUCTS)
Call<List<RelatedProducts>> getProductSureDoYouLike(#Header("Authorization") String auth);
You would then call like so:
apiService.getProductSureDoYouLike("token");
I have to call an api using retrofit 2 in android. but with no values. When I does that, it shows that there must be at least 1 #field. Below is the code I am using.
public interface gitAPI {
#FormUrlEncoded
#POST("/MembersWS.svc/GetMemberAvailability/MBR0011581")
Call<Questions[]> loadQuestions();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.99:82")
.addConverterFactory(GsonConverterFactory.create())
.build();
// prepare call in Retrofit 2.0
gitAPI stackOverflowAPI = retrofit.create(gitAPI.class);
Call<Questions[]> call = stackOverflowAPI.loadQuestions();
call.execute();
Declare body value in your interface with next:
#Body RequestBody body and wrap String JSON object:
RequestBody body = RequestBody.create(MediaType.parse("application/json"), (new JsonObject()).toString());