How do I use Java 11 HttpClient with a proxy server?

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:

  1. 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).
  2. Build HttpClient:
    • The HttpClient is created using the HttpClient.newBuilder() API, and the proxy method is used to assign the custom ProxySelector.
  3. Send an HTTP Request:
    • Create a request using HttpRequest.newBuilder and send the request using HttpClient.send().

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:

  1. Authenticator Class:
    • Use Authenticator.setDefault() to set a global proxy authenticator. Override the getPasswordAuthentication() method to return the credentials for the proxy server.
  2. Proxy and Authentication Configuration:
    • Combine the ProxySelector and the Authenticator to handle both proxy selection and authentication credentials.

Additional Notes:

  • Replace "proxy.example.com" with your proxy server’s hostname and 8080 with the proxy’s port number.
  • Replace proxyUsername and proxyPassword 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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.