本文介绍了如果Java的http代理关闭,它将恢复为非代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真是出乎意料的行为。我正在使用JavaFX WebView 。为了使Web请求通过本地代理,我写了类似的代码:

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");

如果代理正在运行,它似乎工作正常。但是,如果不是,Java会默默地恢复为不使用代理!如果代理不可用,如何强制Java失败?

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?

推荐答案

您可以使用自定义 ProxySelector 只允许你的代理,并且不提供 Proxy.NO_PROXY 作为替代:

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) {}
}

使用 ProxySelector.setDefault(new AlwaysProxySelector())安装此选择器;

这篇关于如果Java的http代理关闭,它将恢复为非代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!