在Java中設置代理可以通過以下幾種方式實現:
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
URL url = new URL("https://example.com");
URLConnection connection = url.openConnection(proxy);
ProxySelector.setDefault(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Handle connection failure
}
});
這些方法可以根據具體的需求選擇適合的方式來設置代理。