简体   繁体   中英

Hard coding Proxy in Java for connecting to specific URL

I have a web app which has to connect to external Web Services (using Axis client). I have to perform 2 things:

  • allow the webapp to go communicate externally using a given HTTP proxy (to authorize the WS clients)
  • use a direct connection when we perform a local call through a URI like

    http://localhost:7001/webApp/getImg?id=22

Note that it works like a charm if we use the system properties (http.proxyHost, etc.) instead of the ProxySelector.

But thing is then all the local calls are routed to the Proxy Server, which I dont want.

So, just a simple question - how to implement a ProxySelector which performs in the same way as when using proxy system properties?

You can achieve this with the system properties by also setting http.nonProxyHosts=localhost . If you want to do it with a ProxySelector then try something like this

final Proxy PROXY = new Proxy(Proxy.Type.HTTP,
  new InetSocketAddress("my.proxy.server", 8080));
ProxySelector.setDefault(new ProxySelector() {
  public List<Proxy> select(URI u) {
    if(u != null && !"localhost".equals(u.getHost())) {
      return Arrays.asList(PROXY, Proxy.NO_PROXY);
    }
    else {
      return Collections.singletonList(Proxy.NO_PROXY);
    }
  }

  public void connectFailed(URI u, SocketAddress sa, IOException e) {
    // do nothing
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM