Java tutorial
/* * Copyright 2015 Xebia Nederland B.V. * * License: * Creative Commons Attribution-NonCommercial 4.0 International * http://creativecommons.org/licenses/by-nc/4.0/ */ package com.xebia.xsdnl.innorater.server; import android.os.Build; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.OkHttpClient; import com.xebia.xsdnl.innorater.BuildConfig; import java.util.Locale; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.converter.GsonConverter; /** * Configures and holds on to the REST client. */ public class Servers { private static RaterService raterService; public static RaterService raterService() { if (raterService == null) { OkHttpClient okHttpClient = new OkHttpClient(); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); final String userAgent = buildUserAgent(); RequestInterceptor standardHeaders = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { // For response compression, AppEngine requires the Accept-Encoding header that // OkHTTP adds automatically *and* the string "gzip" as part of the User-Agent. request.addHeader("User-Agent", userAgent); request.addHeader("Accept", "application/json"); } }; RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(okHttpClient)) .setEndpoint("https://xebia-innovation-day-rater.appspot.com") .setLogLevel(RestAdapter.LogLevel.FULL).setConverter(new GsonConverter(gson)) .setRequestInterceptor(standardHeaders).build(); raterService = restAdapter.create(RaterService.class); } return raterService; } private static String buildUserAgent() { int appVersion = BuildConfig.VERSION_CODE; int androidSdk = Build.VERSION.SDK_INT; // We truncate the Build.VERSION string to 40 chars. I have seen things... String androidVersion = truncate(Build.VERSION.RELEASE); String manufacturer = truncate(Build.MANUFACTURER); String model = truncate(Build.MODEL); return String.format(Locale.US, "InnoRater/%d; (Android/%s; %d; %s; %s) gzip", appVersion, androidVersion, androidSdk, manufacturer, model); } private static String truncate(String raw) { if (raw.length() > 40) { return raw.substring(0, 40); } return raw; } }