Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

java - Set proxy on JavaFX WebEngine?

How can I set a proxy per WebView instance?

This is what I have so far:

public void start(Stage stage) {
    StackPane root = new StackPane();

    WebView view = new WebView();
    WebEngine engine = view.getEngine();
    engine.load("https://www.google.com");
    root.getChildren().add(view);

    Scene scene = new Scene(root, 960, 640);
    stage.setScene(scene);
    stage.show();
}

public static void main(String[] args) throws IOException {
    Application.launch(args);
}

That launches a window with the google page just fine.

However how can I set a proxy? Not the VM system proxy, but a proxy per WebView window.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the deployment overview:

3.2.3 Built-In Proxy Support

Properly packaged JavaFX application have proxy settings initialized according to Java Runtime configuration settings. By default, this means proxy settings will be taken from the current browser if the application is embedded into a web page, or system proxy settings will be used. Proxy settings are initialized by default in all execution modes.

It might not be possible to set per WebView instance. One hack comes to mind, but I really wouldn't want to do it - extend WebView such that whenever the user (and scripts and such in the WebView) interact with it, it calls System.setProperty("http.proxy",this.myProxy). Something like:

class KludgeWebView extends WebView {
  String myProxy;
  String myProxyPort;
  String sysProxy;
  String sysProxyPort;

  KludgeWebView()
  {
    super();

    sysProxy = System.getProperty("http.proxy");
    sysProxyPort = System.getProperty("http.proxyPort");
  }

  public void load(String url)
  {
    useProxy();
    super.load(url);
    revertProxy();
  }

  public void useProxy()
  {
    System.setProperty("http.proxy",myProxy);
    System.setProperty("http.proxyPort", myProxyPort);
  }

  public void revertProxy()
  {
    System.setProperty("http.proxy",sysProxy);
    System.setProperty("http.proxyPort", sysProxyPort);    
  }
}

However, this seems very messy to me. It might miss things like a user clicking on a link inside the WebView, or scripts doing things like XmlHttpRequest. I wouldn't recommend this unless you are left with no other options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...