Skip to content

Instantly share code, notes, and snippets.

@snadjafi
Created September 28, 2014 23:21
Show Gist options
  • Save snadjafi/f89b89713867c764a49a to your computer and use it in GitHub Desktop.
Save snadjafi/f89b89713867c764a49a to your computer and use it in GitHub Desktop.
android retrofit setup example
public final class Api {
//region Variables
private static final String API_HOST = Application.string(R.string.api_server);
private static final Object sLockObject = new Object();
private static Service sService = null;
static final int DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
//endregion
//region Constructor
private Api() {}
//endregion
private Endpoint getEndpoint() {
return Endpoints.newFixedEndpoint(API_HOST);
}
private RequestInterceptor getHeaders() {
return new ApiHeaders();
}
private ErrorHandler getErrorHandler() {
return new ApiErrorHandler();
}
private Client getClient() {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = ImageUtil.getBitmapFromCache("http");
if (cacheDir != null) {
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
}
} catch (IOException e) {
Timber.e(e, "Unable to install disk cache.");
}
client.setSslSocketFactory(createBadSslSocketFactory());
return new OkClient(client);
}
private RestAdapter getRestAdapter() {
return new RestAdapter.Builder()
.setClient(getClient())
.setEndpoint(getEndpoint())
.setRequestInterceptor(getHeaders())
.setErrorHandler(getErrorHandler())
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
}
public static Service getService() {
if (sService != null) {
return sService;
}
// synchronize, re-check the singleton reference, and create if still necessary
synchronized (sLockObject) {
if (sService == null) {
sService = (new Api())
.getRestAdapter()
.create(Service.class);
}
}
return sService;
}
private SSLSocketFactory createBadSslSocketFactory() {
try {
// Construct SSLSocketFactory that accepts any cert.
SSLContext context = SSLContext.getInstance("TLS");
TrustManager permissive = new X509TrustManager() {
@Override public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
context.init(null, new TrustManager[] { permissive }, null);
return context.getSocketFactory();
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
/* Sample of your custom error, you don't have to do this*/
class ApiErrorHandler implements ErrorHandler {
//region Variable
private final Gson mGson;
//endregion
//region Constructor
public ApiErrorHandler() {
mGson = new GsonBuilder().create();
}
//endregion
@Override public Throwable handleError(RetrofitError cause) {
if (cause.getResponse() != null
&& cause.getResponse().getBody().mimeType().equalsIgnoreCase("application/json")) {
InputStreamReader reader;
try {
Response response = cause.getResponse();
reader = new InputStreamReader(response.getBody().in());
ApiError error = mGson.fromJson(reader, ApiError.class);
error.setReason(response.getReason());
error.setUrl(response.getUrl());
error.setStatus(response.getStatus());
return error;
} catch (IOException e) {
Timber.e(e, e.getMessage());
return new ApiError(cause);
}
} else {
return new ApiError(cause);
}
}
}
class ApiHeaders implements RequestInterceptor {
@Override public void intercept(RequestFacade request) {
// adding your custom headers
request.addHeader("User-Agent", "Android");
request.addHeader("S-Version", version);
request.addHeader("S-Device-ID", Device.getID());
request.addHeader("S-OS", "android;" + Build.VERSION.RELEASE);
request.addHeader("S-Device", TextUtils.join(";", deviceDetail));
request.addHeader("Authorization", "token" + " " + Session.getMyToken());
}
}
// usage
Api.getService().ping(new Callback<String>() {
@Override public void success(String response, Response response) {
}
@Override public void failure(RetrofitError error) {
}
}););
public interface Service {
@DELETE("/item")
void checkEligibility(
@Query("id") String id,
CancelableCallback<Response> cb);
@GET("/ping")
void ping(CancelableCallback<String> cb);
@Multipart
@POST("/photo")
PhotoUploadResponse uploadPhoto(@Part("photo") TypedFile photo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment