OkHttp

The sentry-android-okhttp library provides OkHttp support for Sentry via the OkHttp Interceptor. The source can be found on GitHub.

On this page, we get you up and running with Sentry's OkHttp Integration, so that it will automatically add a breadcrumb and start a span out of the active span bound to the scope for each HTTP Request.

Auto-Installation With the Sentry Android Gradle Plugin

Starting from version 3.1.0, the Sentry Android Gradle plugin will automatically add the sentry-android-okhttp dependency and instrument all of your OkHttpClient instances through bytecode manipulation. The plugin will only add the sentry-android-okhttp dependency if an okhttp dependency was discovered on the classpath.

Install

Add the Sentry Android Gradle plugin in build.gradle:

Copied
buildscript {
  repositories {
    mavenCentral()
  }
}

plugins {
  id "io.sentry.android.gradle" version "3.5.0"
}

Then, initialize the Android SDK.

Disable

If you would like to disable the OkHttp instrumentation feature, we expose a configuration option for that:

Copied
import io.sentry.android.gradle.extensions.InstrumentationFeature

sentry {
  tracingInstrumentation {
    enabled = true
    features = EnumSet.allOf(InstrumentationFeature) - InstrumentationFeature.OKHTTP
  }
}

Manual Installation

Install

Sentry captures data by adding an OkHttp Interceptor. To add the OkHttp integration, initialize the Android SDK, then add the sentry-android-okhttp dependency. Using Gradle:

Copied
implementation 'io.sentry:sentry-android:6.18.1'
implementation 'io.sentry:sentry-android-okhttp:6.18.1'

Configure

Configuration should happen once you create your OkHttpClient instance.

Copied
import okhttp3.OkHttpClient
import io.sentry.android.okhttp.SentryOkHttpInterceptor

private val client = OkHttpClient.Builder()
  .addInterceptor(SentryOkHttpInterceptor())
  .build()

Verify

This snippet includes a HTTP Request and captures an intentional message, so you can test that everything is working as soon as you set it up:

Copied
import io.sentry.android.okhttp.SentryOkHttpInterceptor
import io.sentry.Sentry
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.Request

@Throws(IOException::class)
fun run(url: String): String? {
  val request = Request.Builder()
    .url(url)
    .build()

  val bodyStr = client
    .newCall(request)
    .execute()
    .body?.toString()

  Sentry.captureMessage("The Message $bodyStr")

  return bodyStr
}

To view and resolve the recorded message, log into sentry.io and open your project. Clicking on the error's title will open a page where you can see detailed information and mark it as resolved.

Customize the Recorded Span

The captured span can be customized or dropped with a BeforeSpanCallback:

Copied
import io.sentry.ISpan
import io.sentry.android.okhttp.SentryOkHttpInterceptor
import okhttp3.Request
import okhttp3.Response

class CustomBeforeSpanCallback : SentryOkHttpInterceptor.BeforeSpanCallback {
  override fun execute(span: ISpan, request: Request, response: Response?): ISpan? {
    return if (request.url.toUri().toString().contains("/admin")) {
      null
    } else {
      span
    }
  }
}

The callback instance must be set on the SentryOkHttpInterceptor once you create your OkHttpClient instance.

Copied
import okhttp3.OkHttpClient
import io.sentry.android.okhttp.SentryOkHttpInterceptor

private val client = OkHttpClient.Builder()
  .addInterceptor(SentryOkHttpInterceptor(CustomBeforeSpanCallback()))
  .build()

HTTP Client Errors

This feature, once enabled, automatically captures HTTP client errors, like bad response codes, as error events and reports them to Sentry. The error event will contain the request and response data, such as url, status_code, and so on.

This feature is opt-in and can be enabled by setting the captureFailedRequests option to true:

Copied
import okhttp3.OkHttpClient
import io.sentry.android.okhttp.SentryOkHttpInterceptor

private val client = OkHttpClient.Builder()
  .addInterceptor(SentryOkHttpInterceptor(captureFailedRequests = true))
  .build()

By default, only HTTP client errors with a response code between 500 and 599 are captured as error events, but you can change this behavior by setting the failedRequestStatusCodes option:

Copied
import okhttp3.OkHttpClient
import io.sentry.android.okhttp.SentryOkHttpInterceptor
import io.sentry.HttpStatusCodeRange

private val client = OkHttpClient.Builder()
  .addInterceptor(SentryOkHttpInterceptor(
    captureFailedRequests = true,
    failedRequestStatusCodes = listOf(HttpStatusCodeRange(400, 599))))
  .build()

HTTP client errors from every target (.* regular expression) are automatically captured, but you can change this behavior by setting the failedRequestTargets option with either a regular expression or a plain String. A plain string must contain at least one of the items from the list. Plain strings don't have to be full matches, meaning the URL of a request is matched when it contains a string provided through the option.

Copied
import okhttp3.OkHttpClient
import io.sentry.android.okhttp.SentryOkHttpInterceptor
import io.sentry.HttpStatusCodeRange

private val client = OkHttpClient.Builder()
  .addInterceptor(SentryOkHttpInterceptor(
    captureFailedRequests = true,
    failedRequestTargets = listOf("myapi.com")))
  .build()

By default, error events won't contain any PII data, such as Headers and Cookies, but you can change this behavior by setting the sendDefaultPii option to true:

AndroidManifest.xml
Copied
<application>
  <meta-data android:name="io.sentry.send-default-pii" android:value="true" />
</application>

Those events are searchable and you can set alerts on them if you use the http.url and http.status_code properties. Learn more in our full Searchable Properties documentation.

Customize or Drop the Error Event

To customize or drop the error event, you need to do a manual initialization of the Sentry Android SDK.

The captured error event can be customized or dropped with a BeforeSendCallback:

Copied
import io.sentry.android.core.SentryAndroid
import io.sentry.SentryOptions.BeforeSendCallback
import okhttp3.Request
import okhttp3.Response
import io.sentry.TypeCheckHint.OKHTTP_REQUEST
import io.sentry.TypeCheckHint.OKHTTP_RESPONSE

SentryAndroid.init(this) { options ->
  // Add a callback that will be used before the event is sent to Sentry.
  // With this callback, you can modify the event or, when returning null, also discard the event.
  options.beforeSend = BeforeSendCallback { event, hint ->
    val request = hint.getAs(OKHTTP_REQUEST, Request::class.java)
    val response = hint.getAs(OKHTTP_RESPONSE, Response::class.java)

    // customize or drop the event
    event
  }
}

Automatically Captured HTTP Client Errors and Manually Captured Errors

When captureFailedRequests is enabled, some HTTP client libraries throw unchecked exceptions like retrofit2.HttpException. In this case, the error event is captured twice; once by the HTTP client library and once by the Sentry Android SDK:

Copied
import io.sentry.Sentry
import retrofit2.HttpException

try {
  // If this API call returns 500, it will be captured as an error event by the `SentryOkHttpInterceptor`.
  return GithubAPI.service.listReposAsync("getsentry")
} catch (e: HttpException) {
  // Do not manually capture this exception to avoid duplicated error events.
  // Sentry.captureException(e)
}

We recommend you identify those errors and not capture them manually with the Sentry.captureException method.

Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) to suggesting an update ("yeah, this would be better").