Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent OkHttp/Retrofit from bypassing proxy

When OkHttp tries a proxy, and that route fails once, every request after that request will completely bypass the Android system proxy. So it is difficult to debug using Charles.

I currently have the code below, but it is setup to only be for Debug builds. It works great, but it's a hack, and we're looking to release this for all users.

Is there some hidden OkHttpClient.dontBypassProxy setting that I can't find? Or, does the code below look like a good solution?

    OkHttpClient.Builder baseClientBuilder = new OkHttpClient.Builder().retryOnConnectionFailure(false).connectionPool(new ConnectionPool(5, 20, TimeUnit.SECONDS));

    //Ask OkHttp what proxies we have setup
    List<Proxy> proxies = ProxySelector.getDefault().select(URI.create("http://www.somesite.com"));

    if (proxies.size() > 0 && proxies.get(0) != Proxy.NO_PROXY) {
        //Force OkHttp to always use this proxy
        baseClientBuilder.proxy(proxies.get(0));
    }
like image 686
Mike Odie Avatar asked Apr 20 '16 23:04

Mike Odie


1 Answers

This was fixed in OkHttp 3.5.0

https://square.github.io/okhttp/changelog_3x/

OkHttp no longer attempts a direct connection if the system’s HTTP proxy fails. This behavior was surprising because OkHttp was disregarding the user’s specified configuration. If you need to customize proxy fallback behavior, implement your own java.net.ProxySelector.

like image 86
Yuri Schimke Avatar answered Sep 27 '22 22:09

Yuri Schimke