Skip to content

Instantly share code, notes, and snippets.

@eneim
Last active September 13, 2017 11:29
Show Gist options
  • Save eneim/bfe81b4bfa87e1699077 to your computer and use it in GitHub Desktop.
Save eneim/bfe81b4bfa87e1699077 to your computer and use it in GitHub Desktop.
This is how I deal with multi Base Url API
package im.ene.lab.whatever.api;
import com.squareup.okhttp.OkHttpClient;
import retrofit.Call;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.http.GET;
public class GithubIssueHelper {
/**
* The only visible class
*/
public static class PublicApi {
public static void register() {
shoppingApi.register();
}
public static void login() {
meiApi.login();
}
public static void getAge() {
centerApi.setAge();
}
}
private static final OkHttpClient okHttp = new OkHttpClient(); // your http client
// This is the Shared Retrofit Builder I'm talking about
private static final Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.client(okHttp)
.addConverterFactory(GsonConverterFactory.create()); // optional
// Your Base Urls, as many as you want.
private static final String[] BASE_URLS = {
"http://shopping.mlm.com", "http://mei.mlm.com", "http://center.mlm.com"
};
static {
// TODO: you may want to do bunch of setup here, shared between Base Urls
}
/**
* You have 3 base urls, so we create 3 API interface
*/
private interface ShoppingApiService {
@GET("/register") Call<Object> register();
}
private interface MeiApiService {
@GET("/login")
Call<Object> login();
}
private interface CenterApiService {
@GET("/age")
Call<Object> setAge();
}
/**
* For your memory. Not necessary. If you have 1000 of them, just use index.
*/
private static final int SHOPPING_API_INDEX = 0;
private static final int MEI_API_INDEX = 1;
private static final int CENTER_API_INDEX = 2;
/**
* And 3 API helper instance. All are private, invisible to User
*/
private static final ShoppingApiService shoppingApi =
retrofitBuilder.baseUrl(BASE_URLS[/* 0 */ SHOPPING_API_INDEX]).build().create(ShoppingApiService.class);
private static final MeiApiService meiApi =
retrofitBuilder.baseUrl(BASE_URLS[/* 1 */ MEI_API_INDEX]).build().create(MeiApiService.class);
private static final CenterApiService centerApi =
retrofitBuilder.baseUrl(BASE_URLS[/* 2 */ CENTER_API_INDEX]).build().create(CenterApiService.class);
}
@eneim
Copy link
Author

eneim commented Nov 26, 2015

How to use:

Call

GithubIssueHelper.PublicApi.register();

to register.

@xiaomeixw
Copy link

@eneim Thanks for your help, Finally I take your advice in my project...divide interface is a good technical scheme and it work well in my project....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment