3

How can we intercept java.net.HttpURLConnection network requests? However, we can achieve interception using OKHTTPClient. Please help.

Sheela
  • 41
  • 2

1 Answers1

-2

If you want to modify request/response with OkHttpClient you can use interceptors. For example If you want to add a header to all requests, you can use the code below. Modifying other parts like body is similar.

OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();

                Request.Builder builder = originalRequest.newBuilder().header("Authorization",
                        Credentials.basic("aUsername", "aPassword"));

                Request newRequest = builder.build();
                return chain.proceed(newRequest);
            }
        }).build();
Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44