Skip to content

Instantly share code, notes, and snippets.

@efrohnhoefer
Created April 5, 2016 22:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efrohnhoefer/04defbfb2db36e51cbdb6485bc00e010 to your computer and use it in GitHub Desktop.
Save efrohnhoefer/04defbfb2db36e51cbdb6485bc00e010 to your computer and use it in GitHub Desktop.
Code demonstrating how to measure API performance using Answers and OkHttp 2.2+.
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class ApiMetricsInterceptor implements Interceptor {
private final Answers answers;
public ApiMetricsInterceptor(Answers answers) {
this.answers = answers;
}
@Override
public Response intercept(Chain chain) throws IOException {
// Execute the request and measure the elapsed time
final long start = System.nanoTime();
final Response response = chain.proceed(chain.request());
final float elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) / 1000.0f;
final CustomEvent customEvent = new CustomEvent("HTTPRequest");
final Request request = response.request();
final RequestBody requestBody = request.body();
final URL url = request.url();
final ResponseBody responseBody = response.body();
// Set request attributes
customEvent.putCustomAttribute("Host", url.getHost());
customEvent.putCustomAttribute("URL Scheme", url.getProtocol());
customEvent.putCustomAttribute("Sanitized URL", sanitizedUrl(url.getPath()));
customEvent.putCustomAttribute("HTTP Method", request.method());
if (requestBody != null && requestBody.contentLength() != -1) {
customEvent.putCustomAttribute("Data Size", requestBody.contentLength());
}
// Set response attributes
customEvent.putCustomAttribute("Status Code", Integer.toString(response.code()));
customEvent.putCustomAttribute("Elapsed Time", elapsed);
final long contentLength = responseBody.contentLength();
if (contentLength != -1) {
customEvent.putCustomAttribute("Expected Content Length", contentLength);
}
final MediaType contentType = responseBody.contentType();
if (contentType != null) {
customEvent.putCustomAttribute("Content-Type", contentType.toString());
}
// Log custom event
answers.logCustom(customEvent);
return response;
}
String sanitizedUrl (String path) {
// Make sure path is less than 100 chars
// Remove sensitive data
return path;
}
}
@efrohnhoefer
Copy link
Author

screen shot 2016-04-05 at 4 01 23 pm

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