简体   繁体   中英

Configuring HTTPS proxy in Java

Is there any way to configure HTTPS proxy using java.net.Proxy class? I want to communicate with an HTTP destination using HTTPS proxy from a Java client.

Thanks in advance.

Here is a minimalistic example of how to set up proxying programmatically:

SocketAddress a = new InetSocketAddress("proxy.example.com", 8080);
Proxy p = new Proxy(Proxy.Type.HTTP, a);
ProxySelector ps = new ProxySelector() {
    public List<Proxy> select(URI uri) { return Collections.singletonList(p); }
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
};
ProxySelector.setDefault(ps);

Real code should of course do something sensible in connectFailed , and check the URI scheme in select if the application will also be using other schemes that are not supported by the proxy server. In the latter case it should return a Proxy instance that has the type Proxy.Type.DIRECT , which will cause the connection to bypass the proxy.

I have only used this with http and https URLs, so I don't know if it works with any other schemes. For https URLs the proxy server needs to support the CONNECT method.

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