How to add headers to OkHttp request interceptor?

前端 未结 10 1496
感情败类
感情败类 2020-12-01 00:24

I have this interceptor that i add to my OkHttp client:

public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Cha         


        
相关标签:
10条回答
  • 2020-12-01 01:14

    Kotlin version:

    fun okHttpClientFactory(): OkHttpClient {
        return OkHttpClient().newBuilder()
            .addInterceptor { chain ->
                chain.request().newBuilder()
                    .addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                    .build()
                    .let(chain::proceed)
            }
            .build()
    }
    
    
    0 讨论(0)
  • 2020-12-01 01:15

    There is yet an another way to add interceptors in your OkHttp3 (latest version as of now) , that is you add the interceptors to your Okhttp builder

    okhttpBuilder.networkInterceptors().add(chain -> {
     //todo add headers etc to your AuthorisedRequest
    
      return chain.proceed(yourAuthorisedRequest);
    });
    

    and finally build your okHttpClient from this builder

    OkHttpClient client = builder.build();
    
    0 讨论(0)
  • 2020-12-01 01:16

    you can do it this way

    private String GET(String url, Map<String, String> header) throws IOException {
            Headers headerbuild = Headers.of(header);
            Request request = new Request.Builder().url(url).headers(headerbuild).
                            build();
    
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
    
    0 讨论(0)
  • 2020-12-01 01:20

    Finally, I added the headers this way:

    @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request();
            Request newRequest;
    
            newRequest = request.newBuilder()
                    .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                    .addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
                    .build();
            return chain.proceed(newRequest);
        }
    
    0 讨论(0)
提交回复
热议问题