How to add a title to the OkHttp request object that was created?

I want to add a header to the OkHttp request object that has already been created. Should I call newBuilder() on request? What does newBuilder() do?

+6
source share
1 answer

If this is just a one-time insertion of the header on the Request , then it is mandatory: request.newBuilder().addHeader("header-name", "value").build();

If you want to do this for all Request in OkHttpClient , use an interceptor:

 private static final class AddHeaderInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); request = request.newBuilder().addHeader("header-name", "value").build(); return chain.proceed(request); } } 

Regarding what newBuilder () does, read the source. :) https://github.com/square/okhttp/blob/0ac2471d0678dfa9d535fbb13a546134dc2b3089/okhttp/src/main/java/com/squareup/okhttp/Reest.quest

+8
source

All Articles