If Java's http proxy is down, it reverts to no

2019-08-19 02:00发布

问题:

This is really unexpected behavior. I'm writing a simple web browser using the JavaFX WebView. To make the web requests go through a local proxy, I wrote code similar to this:

System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "8080");

It appears to work fine if the proxy is running. However, if it isn't, Java silently reverts to not using a proxy at all! How can I force Java to fail if the proxy is not available?

回答1:

You may be able to do this with a custom ProxySelector which only allows your proxy, and doesn't offer Proxy.NO_PROXY as an alternative:

import java.net.*;
import java.util.*;

public class AlwaysProxySelector implements ProxySelector {
  private List<Proxy> proxies = Arrays.asList(new Proxy[] {
        new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080))
      });

  public List<Proxy> select(URI u) { return proxies; }
  public void connectFailed(URI u, SocketAddress a, IOException e) {}
}

You install this selector using ProxySelector.setDefault(new AlwaysProxySelector());



回答2:

Vasily, one of the WebView developers, provided some sample code to track load operation status when working with a proxy. Not sure if it will help, but you could take a look at it.

Vasily, also notes:

At the moment, WebEngine provides no special support for proxy or, more generally, HTTP authentication, but relies on what the java.net.* stack offers in that area.

If you bundle your application using the JavaFX packaging tasks:

The main application JAR file will include a launcher program that takes care of the bootstrap launch... Setting the system proxy for your application

Also, make sure you are using a the latest version of JavaFX as earlier versions had bugs around some of the proxy handling.

There is a guide to proxies and in it, it mentions that https has it's own proxy handler: (https.proxyHost and https.proxyPort), so that is also something to be aware of if your browser will be making https connections.