How can we intercept java.net.HttpURLConnection network requests? However, we can achieve interception using OKHTTPClient. Please help.
Asked
Active
Viewed 1,875 times
1 Answers
-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
-
4Thanks. Question is how we can intercept HTTPURLConnection network calls? – Sheela May 29 '18 at 08:54