Skip to content

NewRelic.addHTTPHeadersTrackingFor should allow tracking headers in the response #339

@luongvo

Description

@luongvo

Summary

We're working on a project that needs to track some custom headers that the API returns in the OkHttp Response. NewRelic.addHTTPHeadersTrackingFor supports tracking Request headers, not the Response headers.

While waiting for the official support, we had a deal with a workaround to bring expected headers from the response.headers to the response.request.headers for NR to track using Reflection 😢

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        ...
        return chain.proceed(request).apply {
            mapResponseHeadersToRequestHeaders()
        }
    }

    private fun Response.mapResponseHeadersToRequestHeaders() = try {
        val responseHeaders = this.headers
        val requestHeaders = this.request.headers

        Class.forName("okhttp3.Headers")
            .getDeclaredField("namesAndValues")
            .apply { isAccessible = true }
            .let { field ->
                var namesAndValues = field.get(requestHeaders) as Array<String>
                namesAndValues += "custom-header"
                namesAndValues += responseHeaders["custom-header"].orEmpty()
                field.set(requestHeaders, namesAndValues)
            }
    } catch (e: Exception) {
        e.printStackTrace()
    }

Desired Behavior

Allow to track headers from the Response headers, instead of only from the Request headers.

Possible Solution

Mainly need to be updated within https://github.com/newrelic/newrelic-android-agent/blob/develop/agent-core/src/main/java/com/newrelic/agent/android/instrumentation/okhttp3/OkHttp3TransactionStateUtil.java.

Additional context

Using a workaround above with Reflection should still work, but Reflection is not the recommended solution for production usage. Also, having an additional step to map expected headers from the Response object to the Request object per request is not an ideal solution.

This feature requires this bug fix #210.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions