How do I use Proxy class to configure HTTP and SOCKS proxies in Java?

In Java, the Proxy class (available in the java.net package) allows you to configure and use HTTP or SOCKS proxies when making network connections. With this class, you can control the routing of requests through a proxy server.
Here’s an explanation and examples of how to use the Proxy class for both HTTP and SOCKS proxies:

1. Creating a Proxy Instance

To use a proxy, you create an instance of the Proxy class by specifying:
– A Proxy.Type (HTTP or SOCKS).
– An address or host of the proxy server using the InetSocketAddress.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));

For SOCKS proxies:

Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("proxy.example.com", 1080));

2. Using Proxy with HttpURLConnection

When making HTTP requests using HttpURLConnection, you pass the created Proxy instance to the openConnection() method:

package org.kodejava.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

public class ProxyExample {
    public static void main(String[] args) {
        try {
            // Proxy configuration
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));

            // URL to connect to
            URL url = new URL("https://www.example.com");

            // Open connection with the proxy
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);

            // Send GET request
            connection.setRequestMethod("GET");

            // Reading response
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Using Proxy with Socket Connections

The Proxy class can also be used with raw Socket or SocketChannel for SOCKS proxies:

package org.kodejava.net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;

public class SocksProxyExample {
    public static void main(String[] args) {
        try {
            // Create a SOCKS proxy
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socksproxy.example.com", 1080));

            // Connect to a host through the proxy
            Socket socket = new Socket(proxy);
            socket.connect(new InetSocketAddress("example.com", 80));

            // Send HTTP request manually
            OutputStream output = socket.getOutputStream();
            output.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".getBytes());
            output.flush();

            // Read response
            InputStream input = socket.getInputStream();
            int data;
            while ((data = input.read()) != -1) {
                System.out.print((char) data);
            }

            // Close the connection
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. Global Proxy Configuration

If you want to configure a proxy globally for all network connections, you can set system properties:
For HTTP proxy:

System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");

For HTTPS proxy:

System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");

For SOCKS proxy:

System.setProperty("socksProxyHost", "socksproxy.example.com");
System.setProperty("socksProxyPort", "1080");

To disable certain hosts (bypass proxy):

System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1|*.example.com");

5. Proxy Authentication

If your proxy requires authentication, you need to configure an Authenticator:

package org.kodejava.net;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class ProxyAuthenticator {
    public static void main(String[] args) {
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password".toCharArray());
            }
        });

        // Set the global proxy settings
        System.setProperty("http.proxyHost", "proxy.example.com");
        System.setProperty("http.proxyPort", "8080");

        // Make HTTP requests as usual
    }
}

Choosing Between Proxy and Global Configuration

  • Use the Proxy class if you only want specific connections to use a proxy.
  • Use global properties (System.setProperty) if the proxy should be used for all connections.
Wayan

Leave a Reply

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