I have following server Urls:
server-base-url/method1
server-base-url/method2
server-base-url/method3
...
server-base-url/method100
I am currently using a properties file to store the URLs. When I need to consume some of the server URLs, then I read the properties file and perform the http request using Spring 4 Android
I know that should be another way (and a better way) to do this. What is the best practice to achieve this?
Another Option is to use Plain Java:
public class ServerInfo {
private static final String URL_BASE_DEBUG = "your base debug url";
private static final String URL_BASE_RELEASE = "your base release url";
public static String getBaseUrl() {
//change if debug' release or whichever flavor
return URL_BASE_DEBUG;
}
}
It's pretty straight forward...You can have all the information needed in a single Java Class
Now regarding the network comm It's really up to you...There are many choices...I personally like Retrofit 2 which is a wrapper on top of a networking library okhttp
A short example of how you can use Retrofit
with the above method is:
Rest Api (like User Rest api)
public interface SomeRestApiEndPoints {
@GET("api/method1")
Call<ReturnValue> method1(params);
@POST(api/method2)
Call<ReturnObject> method2(params);
...
}
The Rest Client
public class RestClient {
private static RestClient sRestClient;
private Retrofit mRetrofit;
private SomeRestApiEndPoints apiEndpoint;
public static RestClient getRestClient () {
if(sRestClient != null){
return sRestClient;
}
synchronized (RestClient.class) {
if(sRestClient == null) {
//gson example
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
RestClient client = new RestClient();
client.mRetrofit = new Retrofit.Builder()
.baseUrl(ServerInfo.getBaseUrl()) //This is where you bind the base Url
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
client.apiEndpoint = client.mRetrofit.create(SomeRestApiEndPoints.class);
sRestClient = client;
}
return sRestClient;
}
public SomeRestApiEndPoints getApi() {
return apiEndpoints;
}
}
Usage Example
Call<ReturnValue> call = RestClient.getRestClient().getApi().method1(params);