Hello!

I use the following construction to access HTTP servers:

URL url = new URL(sUrl); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyElement.getIP(), proxyElement.getPort())); HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(proxy); 

There were questions:

  1. How to interrupt the connection by timeout, sometimes it happens that the proxy "hangs" without an answer?
  2. How can I get around specifying the exact type of proxy? Is it possible to somehow determine it before connecting?

    1 answer 1

    A more convenient way to implement a connection through a proxy is to use the ProxySelector class.

    He is able to respond normally to the case if the proxy server is unavailable ( failed in implementation) and more closely matches the factory ideology that should be used here.

    A good example of how to use it is.

    • I read about this method, but where does it get the proxy list? The proxy server may be available, but to be very slow, I need to get around it. - Dex
    • @Dex ProxySelector is just an abstract class that extends independently. That is, you need to follow it and implement the select and connectionFailed methods (see example). If you want to discard slow proxy servers, you can either ping them once every X seconds inside the ProxySelector itself, or ping them before returning from the select method, and, accordingly, either send them as a result or try another one. - Costantino Rupert
    • @Dex It’s still good that the whole logic of choosing proxies obviously goes inside the class inherited from ProxySelector and outside this class you don’t have to worry about anything. You can go even further and, for example, make implementations of OnlyFastProxySelector and AnyProxySelector , which, obviously, will return only fast or any proxies, respectively. - Costantino Rupert
    • @ Kotik_khohet_kusat, it works always when there is access to the network? - Dex