Home > Java > javaTutorial > body text

How to Configure HttpURLConnection to Use a Proxy?

Linda Hamilton
Release: 2024-11-07 20:06:03
Original
200 people have browsed it

How to Configure HttpURLConnection to Use a Proxy?

How to Configure HttpURLConnection to Use a Proxy

When attempting to establish an HTTP connection without explicitly setting a proxy, it may not respect the system proxy settings. To resolve this, there are methods to configure HttpURLConnection explicitly to use a proxy.

In Java 1.5 and later, an HttpURLConnection can be configured to use a proxy by passing in a java.net.Proxy instance to the openConnection(proxy) method. For example:

// Proxy instance with IP address 10.0.0.1 and port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection(proxy);
Copy after login

If the proxy requires authentication, it will respond with an HTTP 407 error. To handle this, an Authenticator can be used:

Authenticator authenticator = new Authenticator() {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "password".toCharArray());
    }
};
Authenticator.setDefault(authenticator);
Copy after login

Setting the default Authenticator will provide the credentials necessary for the proxy authentication. By utilizing these methods, the HttpURLConnection will effectively use the provided proxy settings.

The above is the detailed content of How to Configure HttpURLConnection to Use a Proxy?. 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