Configure the forward proxy on OkHttp, then supply that same client to Retrofit:

import java.net.InetSocketAddress;
import java.net.Proxy;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

Proxy proxy = new Proxy(
    Proxy.Type.HTTP,
    new InetSocketAddress("proxy.example", 8080));

OkHttpClient http = new OkHttpClient.Builder()
    .proxy(proxy)
    .build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example/")
    .client(http)
    .build();

The fragment builds the transport and Retrofit instance. Add the application’s required converter and call-adapter factories to this builder before build, then create its service interface from this instance.

Keep baseUrl set to the actual API service. Substituting the proxy URL there changes the HTTP destination; it does not configure proxy negotiation. The base URL also retains Retrofit’s trailing-slash requirement. A permitted public-API test without proxy authentication can take an HTTP address from the HTTP proxy list for the separate Proxy object.

An explicit OkHttp proxy takes precedence over its ProxySelector. Use this when the client should have a fixed intermediary. Applications that need destination-dependent routing should design that policy through the supported selector instead.

If the service interface was already created from another Retrofit instance, building this new instance does not move the old interface’s requests. Keep the configured client, Retrofit instance and service object on the same construction path.

For an authenticated proxy, OkHttp exposes proxyAuthenticator separately from its destination authenticator. Configure that on the OkHttp builder when required, then pass the completed client into Retrofit. For a Basic-authenticating proxy, use bounded proxyAuthenticator retry handling.

متعلقہ مضامین