To use Java 11’s HttpClient
with a proxy server, you need to configure the proxy using the ProxySelector
class. The ProxySelector
allows you to specify a proxy through which HTTP requests should pass.
Here’s an example of how you can configure and use HttpClient
with a proxy server:
Step-by-Step Example
Example with Proxy Configuration
package org.kodejava.net.http;
import java.io.IOException;
import java.net.*;
import java.net.http.*;
import java.util.List;
public class HttpClientWithProxyExample {
public static void main(String[] args) {
// Create a ProxySelector with a specified proxy server
ProxySelector proxySelector = new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
// Returning the proxy details
return List.of(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.err.println("Proxy connection failed: " + ioe.getMessage());
}
};
// Build an HttpClient with the proxy selector
HttpClient httpClient = HttpClient.newBuilder()
.proxy(proxySelector)
.build();
// Create an HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.GET()
.build();
try {
// Send the request
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response status code: " + response.statusCode());
System.out.println("Response body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Key Points in the Example:
- ProxySelector Implementation:
- A custom
ProxySelector
is created, which is capable of specifying a proxy (Proxy.Type.HTTP
) and its hostname (proxy.example.com
) and port (8080
).
- A custom
- Build HttpClient:
- The
HttpClient
is created using theHttpClient.newBuilder()
API, and theproxy
method is used to assign the customProxySelector
.
- The
- Send an HTTP Request:
- Create a request using
HttpRequest.newBuilder
and send the request usingHttpClient.send()
.
- Create a request using
Example with Proxy Authentication
If your proxy server requires authentication, you can configure it using the Authenticator
class:
package org.kodejava.net.http;
import java.io.IOException;
import java.net.*;
import java.net.http.*;
import java.util.List;
public class HttpClientWithProxyAuthExample {
public static void main(String[] args) {
// Set system-wide default authenticator
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication("proxyUsername", "proxyPassword".toCharArray());
}
return null;
}
});
// Create ProxySelector with proxy details
ProxySelector proxySelector = new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
return List.of(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
System.err.println("Proxy connection failed: " + ioe.getMessage());
}
};
// Build the HttpClient with the proxy selector and default authenticator
HttpClient httpClient = HttpClient.newBuilder()
.proxy(proxySelector)
.authenticator(Authenticator.getDefault())
.build();
// Create an HTTP Request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.GET()
.build();
try {
// Send HTTP request
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response status code: " + response.statusCode());
System.out.println("Response body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Key Points in Proxy Authentication:
- Authenticator Class:
- Use
Authenticator.setDefault()
to set a global proxy authenticator. Override thegetPasswordAuthentication()
method to return the credentials for the proxy server.
- Use
- Proxy and Authentication Configuration:
- Combine the
ProxySelector
and theAuthenticator
to handle both proxy selection and authentication credentials.
- Combine the
Additional Notes:
- Replace
"proxy.example.com"
with your proxy server’s hostname and8080
with the proxy’s port number. - Replace
proxyUsername
andproxyPassword
with the credentials required for accessing the proxy server. - For HTTPS requests, ensure the proxy supports secure traffic.
This approach allows you to work with both HTTP and HTTPS requests through a proxy server.