Home >Java >javaTutorial >How to Configure HTTP Proxy Settings for HttpURLConnection?
HTTP Proxy Configuration for HttpURLConnection
The inability of HttpURLConnection to use proxy settings can be puzzling for developers working behind firewalls. Despite the presence of proxy information in the JVM, the connection may still establish without proxy usage.
Java 1.5 and Above:
Introducing Java 1.5 brought a significant change to proxy configuration. Developers can now explicitly specify a proxy instance using the openConnection(proxy) method:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080)); conn = new URL(urlString).openConnection(proxy);
Authentication Handling:
If your proxy requires authentication, you will encounter a 407 response code. To address this, implement a custom Authenticator subclass and set it as the default authenticator:
Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { // Provide appropriate credentials for proxy authentication return new PasswordAuthentication("user", "password".toCharArray()); } }; Authenticator.setDefault(authenticator);
By implementing this solution, you instruct HttpURLConnection to utilize the specified proxy, ensuring successful connectivity through the firewall.
The above is the detailed content of How to Configure HTTP Proxy Settings for HttpURLConnection?. For more information, please follow other related articles on the PHP Chinese website!