如何将标头添加到已构建的OkHttp请求对象?

时间:2015-09-29 00:12:13

标签: java android okhttp

我想为已经构建的OkHttp请求对象添加标头。我应该根据要求拨打newBuilder()吗? newBuilder()做了什么?

1 个答案:

答案 0 :(得分:9)

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

If you want to do this for all Requests in your 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);
  }
}

As for what newBuilder() does, read the source. :) https://github.com/square/okhttp/blob/0ac2471d0678dfa9d535fbb13a546134dc2b3089/okhttp/src/main/java/com/squareup/okhttp/Request.java#L93