square / okhttp

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

Home Page:https://square.github.io/okhttp/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possibility to use addUnsafeNonAscii header on Request.Builder

iruizmar opened this issue · comments

When trying to add new headers inside an interceptor, I usually do the following:

OkHttpClient.Builder()
    .addInterceptor { chain ->
        chain.proceed(
             chain.request()
                 .newBuilder()
                 .addHeader(X, Y)
                 .build()
        )
    }

But what if I want to use the internal header builder addUnsafeNonAscii method? There isn't any shortcut for that.
The workaround is something like:

OkHttpClient.Builder()
    .addInterceptor { chain ->
        chain.proceed(
             chain.request()
                 .newBuilder()
                 //We need to use headers already in the request.
                 .headers(chain.request().headers.newBuilder().apply {
                     addUnsafeNonAscii(X, Y)
                 }.build())
                 .build()
        )
    }

It would be easy to add a new addUnsafeNonAscii method to Request.Builder that will use the internal header builder's addUnsafeNonAscii.

This was a deliberate API decision #4296 (comment)

I think it's the right call, technically possible but not a suggestion on the easy path. Since it's possible but more verbose, I'm going to close this.