Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use multiple baseurl in retrofit?

I want to use two server url using retrofit, but only one is working when I am using two base url. Please tell me how to use two base url in android.

public class APIUtils {
    public static String Url1 = "http://10.0.13.46:19460";
    public static String Url12 = "http://freshcamera.herokuapp.com";


    public static SOService getSOService(String url) {
        return RetrofitClient.getClient(url1).create(SOService.class);
    }

}

SOService class

public interface SOService {


   //URL 2
    @FormUrlEncoded
    @POST("/api/user/LoginUser")
    Call<Login> Login(@Field("username") String username, @Field("password")String password, @Field("grant_type")String passwords);
}

SOService_AI class

public interface SOService_AI {


    //URL 1
    @FormUrlEncoded
    @POST("/finalresult1")
    Call<List<AIImageProcessing>> AiImageCheck(@Field("img_data") String imgdata, @Field("name")String imgName);


}
like image 204
Anshul Khare Avatar asked Apr 23 '18 07:04

Anshul Khare


People also ask

How do I use two base urls in retrofit?

For example, the following code will override the URL passed as baseUrl to retrofit object. @GET public Call<ResponseBody> profilePicture(@Url String url); Note: You can't add url param to @GET and @POST . The URL must be passed to @Url .

How do I change my retrofit URL on Android?

For latest Retrofit library, you can simply use singleton instance and change it with retrofitInstance. newBuilder(). baseUrl(newUrl) . No need to create another instance.


3 Answers

I guess what you need is changing URL at runtime to a completely different one.

For example, the following code will override the URL passed as baseUrl to retrofit object.

@GET
public Call<ResponseBody> profilePicture(@Url String url);

Note: You can't add url param to @GET and @POST. The URL must be passed to @Url.

// ERROR ( @Url cannot be used with @GET URL)
@GET("users") // or POST
public Call<Foo> getUsers(@Url String url);

// CORRECT
@GET
public Call<Foo> getUsers(@Url String fullUrl);

Checkout this tutorial for further information.

like image 64
Mahdi-Malv Avatar answered Sep 20 '22 14:09

Mahdi-Malv


with Kotlin its even easier

companion object {
    // init Retrofit base server instance
    val redditClient by lazy { ApiService.invoke(REDDIT_BASE_URL) }
    val stackClient by lazy { ApiService.invoke(STACK_BASE_URL) }

    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.BODY
    }

    operator fun invoke(baseUrl: String): ApiService {
        val client = OkHttpClient.Builder().apply {
            /**addNetworkInterceptor(StethoInterceptor()) */
            addNetworkInterceptor(loggingInterceptor)
            connectTimeout(10, TimeUnit.MINUTES)
            readTimeout(10, TimeUnit.MINUTES)
            writeTimeout(10, TimeUnit.MINUTES)
        }.build()

        return Retrofit.Builder()
            .client(client)
            .baseUrl(baseUrl)
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}

just pass the baseUrl in the invoke method

like image 31
itzik pichhadze Avatar answered Sep 22 '22 14:09

itzik pichhadze


if you are working two url then you create two retrofit object. because single retrofit object work on single url. if you want to access two your make two retofit object like below code..

public class ApiClient {
private final static String BASE_URL = "https://simplifiedcoding.net/demos/";
private final static String BASE_URL2 = "http://freshcamera.herokuapp.com";

public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2=null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}

public Retrofit getClient2() {
    return getClient2(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
private Retrofit getClient2(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL2)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

}

then after access like below code ..

        ApiClient.getInstance().getClient();
    ApiClient.getInstance().getClient2();
like image 24
Android Team Avatar answered Sep 18 '22 14:09

Android Team