Home  >  Article  >  Java  >  How to Configure HttpURLConnection to Use a Proxy?

How to Configure HttpURLConnection to Use a Proxy?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 20:06:03129browse

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);

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);

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!

Statement:
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