I have a helper class that does HTTP operations on Android. Every method uses a client field. I think it's a good idea to make this client a singleton since every method in the class uses it.
The problem is that I don't know 100% what's the best way to implement this singleton since it's only a field in my helper class.
public class HttpHelper {
private static OkHttpClient client;
private HttpHelper() { }
private static OkHttpClient getClient() {
if(client == null) {
client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT, TimeUnit.SECONDS);
}
return client;
}
// method that uses client:
public static String getHTML(String cookie, String URL) throws IOException {
Request request = new Request.Builder().url(URL).header("Cookie", cookie).build();
Response response = getClient().newCall(request).execute(); // using client
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return readStream(response.body().byteStream());
}
}
I am using methods like getHTML()
(yes, the class has more) all over my project.
Is it OK that I use a lot of static methods like
getHTML()
?Should I be implementing the
HttpHelper
class as singleton and use non static methods likeHttpHelper.getInstance().getHTML()
(where the client is created in thegetInstance()
method of theHttpHelper
?