乐闻世界logo
搜索文章和话题

How do I make HttpURLConnection use a proxy?

1个答案

1

In Java, the HttpURLConnection class is used for sending and receiving data, typically for sending HTTP requests and receiving HTTP responses. When you need to send requests through a proxy server, you can configure HttpURLConnection to use a proxy in multiple ways.

1. Configuring Proxy Using the Proxy Class

The most straightforward approach is to use the Proxy class when creating an instance of HttpURLConnection. Here is a specific example:

java
import java.net.*; public class ProxyExample { public static void main(String[] args) { try { URL url = new URL("http://example.com"); // Create the address and port for the proxy server Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy server address", proxy server port)); // Open the connection through the proxy HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); // Set request method, timeout, and other parameters connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // Send request and retrieve response code int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }

In this example, we first create a Proxy object, which requires Proxy.Type and InetSocketAddress (the proxy server's IP address and port). Then we use this proxy object to establish the HttpURLConnection.

2. Configuring Global Proxy Using System Properties

If you want to apply the same proxy to all HTTP connections, you can achieve this by setting system properties. This method affects all HttpURLConnection instances created within the application.

java
public class GlobalProxyExample { public static void main(String[] args) { try { // Set global proxy configuration System.setProperty("http.proxyHost", "proxy server address"); System.setProperty("http.proxyPort", "proxy server port"); URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set request method, timeout, and other parameters connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // Send request and retrieve response code int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }

In this example, we use System.setProperty to define the proxy server address and port, which will apply to all HttpURLConnection instances.

Conclusion

The choice depends on your specific requirements. If only some requests need to go through a proxy, using the Proxy class is a good option. If you want all HTTP requests in your application to use the same proxy, setting system properties may be more convenient.

2024年8月5日 01:15 回复

你的答案