Home > Java > javaTutorial > body text

How to Configure HTTP Proxy Settings for HttpURLConnection?

Barbara Streisand
Release: 2024-11-07 21:53:02
Original
479 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!