How to configure the proxy parameters for Java?


How to configure the proxy parameters for Java?

In today’s network environments, categorically those of companies, application developers have to deal with proxys almost as often as system administrators. In some cases, the application must use the system default settings, in other cases, it will be an additive to have very strict control over what goes through which proxy, and, somewhere in the middle, most applications will be happy to delegate the decision to their users by providing them with a graphical interface to define the proxy parameters, as is the case in most browsers.

Proxy servers act as interfaces between client applications and other servers. In a business environment, we often use them to help control the content that users consume, usually beyond the limits of the network.

Approaches:

We will discover two ways to connect via proxy servers in Java, which are as follows:

  1. Branched approach to the JVM scale and configured with system properties.
  2. Use of the Proxy class which offers more control by authorizing configuration on the basis of each connection.

Method 1: Use of a global parameter

Java has a set of system properties that can be used to configure behavior across the JVM. This “universal” approach is often the simplest to implement if it is suitable for use. We can define the properties required from the command line when invoking the JVM. Alternatively, we can also define them using System.setProperty () at the time of execution. Here is how to define them using the command line, as shown below:

2.1. Define via command line arguments

We can define proxys on the control line bypassing the parameters as system properties:

java -Dhttp.proxyHost = 127.0.0.1 -Dhttp.proxyPort = 8080 com.geeksforgeeks.networking.proxies.CommandLineProxyDemo

When you start a process this way, we can just use it openConnection () on the URL without additional work:

2.3 Define the proxy using the System.setProperty () method

If there are problems using the command line, there is another way to do this using the System.setProperty () method. To configure a proxy.

System.setProperty (“http.proxyHost”, “127.0.0.1″) ;

System.setProperty (“http.proxyPort”, “8080”) ;

URL URL = new URL (RESOURCE_URL) ;

URLConnection con = url.openConnection () ;

// …

If we then manually deactivate the relevant system properties, the proxy will no longer be used:

Now, with that, there are global configuration limitations that are described below.

  • The global configuration approach is the simplest way to define the proxy, but there are certain limitations to this approach.
  • This approach provides the implementation on the JVM at scale, so that the parameters defined for a particular protocol are active during the life of the JVM or until we deactivate them manually.

Note: To overcome this limitation, it may be interesting to activate and deactivate the parameters, if necessary. However, it would be necessary to ensure protective measures against competition problems in a multi-thread program.

Thus, as an alternative, the API Proxy is more efficient and offers more control over the configuration of the proxy. As an alternative, the Proxy API provides more granular control over the configuration of the proxy. This gives rise to another approach than via Proxy API

Method 2: Use of the proxy API

The Proxy class offers us a flexible way to configure proxys by connection. If there are JVM-wide proxy parameters, connection-based proxy parameters using the Proxy class will replace them. Here are three types of proxy that we can define by type of proxy :

  1. HTTP is a proxy using the HTTP protocol
  2. SOCKS is a proxy using the SOCKS protocol
  3. DIRECT is a direct connection explicitly configured without proxy

(A) Use of an HTTP proxy

To use an HTTP proxy, we first wrap a SocketAddress instance with a proxy and the Proxy.Type.HTTP type. Then we simply pass the Proxy instance to URLConnection.openConnection ():

URL weburl = new URL (URL_STRING) ;

Proxy webProxy = new Proxy (Proxy.Type.HTTP, new InetSocketAddress (“127.0.0.1”, 8080)) ;

HttpURLConnection webProxyConnection = (HttpURLConnection) weburl.openConnection (webProxy) ;

Now let’s connect to URL_STRING, then route this connection via a proxy server hosted at 127.0.0.1: 8080.

(B) Use of a DIRECT proxy

We may need to connect directly to a host. In this case, we can explicitly bypass a proxy which can be configured globally using the static instance Proxy.NO_PROXY. Under the covers, the API is building a new Proxy instance for us, using Proxy.Type.DIRECT as a type:

HttpURLConnection directConnection = (HttpURLConnection) weburl.openConnection (Proxy.NO_PROXY) ;

(C) Use of a SOCKS proxy

The Socks proxy works in a similar way to the HTTP variant while treating URLConnection. In the Socks proxy, we first wrap a SocketAddress instance with a proxy using the Proxy.Type.SOCKS type. After that, the proxy instance is transmitted to URLConnection.openConnection.

Proxy socksProxy = new Proxy (Proxy.Type.SOCKS, new InetSocketAddress (“127.0.0.1”, 1080)) ;

HttpURLConnection socksConnection = (HttpURLConnection) weburl.openConnection (socksProxy) ;

It is also possible to use a SOCKS proxy when connecting to a TCP socket. First, we use the Proxy instance to build a Socket. Then we move the SocketAddress destination instance to Socket.connect () as follows:

Socket proxySocket = new Socket (socksProxy) ;

InetSocketAddress socketHost = new InetSocketAddress (SOCKET_SERVER_HOST, SOCKET_SERVER_PORT) ;

proxySocket.connect (socketHost) ;

Example:

// Java Program to Create a Simple Proxy Server
  
// Importing input output classes
import java.io.* ;
// Importing
import java.net.* ;
  
public class SimpleProxyServer {
    public static void main (String [] args)
        IOException throws
    {
        try {
            String host = "your Proxy Server" ;
            int remoteport = 100 ;
            int localport = 111 ;
            // Print a start-up message
            System.out.println ("Starting proxy for" + host
                               + ":" + remoteport
                               + "on port" + localport) ;
            // And start running the server
            runServer (host, return,
                      localport); // never returns
        }
        wrestling (Exception e) {
            System.err.println (e) ;
        }
    }
  
    / **
     * runs a single-threaded proxy server on
     * the specified local port. It never returns.
     * /
    public static void
    runServer (String host, int remoteport, int localport)
        IOException throws
    {
        // Create a ServerSocket to listen for connections
        // with
        ServerSocket ss = new ServerSocket (localport) ;
  
        final byte [] request = new byte [1024] ;
        byte [] reply = new byte [4096] ;
  
        while (true) {
            Customer socket = null, server = null ;
            try {
                // Wait for a connection on the local port
                client = ss.accept () ;
  
                final InputStream streamFromClient
                    = client.getInputStream () ;
                final OutputStream streamToClient
                    = client.getOutputStream () ;
  
                // Make a connection to the real server.
                // If we cannot connect to the server, send
                // an error to the client, disconnect, and
                // continue waiting for connections.
                try {
                    server = new Socket (host, remote report) ;
                }
                wrestling (IOException e) {
                    PrintWriter out
                        = new PrintWriter (streamToClient) ;
                    out.print (
                        "Proxy server cannot connect to"
                        + host + ":" + remote report + ":  n"
                        + e + " n") ;
                    out.flush () ;
                    client.close () ;
                    keep on going;
                }
  
                // Get server streams.
                final InputStream streamFromServer
                    = server.getInputStream () ;
                final OutputStream streamToServer
                    = server.getOutputStream () ;
  
                // a thread to read the client's requests
                // and pass them to the server. A separate
                // thread for asynchronous.
                Thread t = new Thread () {
                    public void run ()
                    {
                        int bytesRead ;
                        try {
                            while ((bytesRead
                                    = streamFromClient.read (
                                        request))
                                   = -1) {!                                streamToServer.write (
                                    request, 0, bytesRead) ;
                                streamToServer.flush () ;
                            }
                        }
                        wrestling (IOException e) {
                        }
  
                        // the client closed the connection
                        // to us, so close our connection to
                        // the server.
                        try {
                            streamToServer.close () ;
                        }
                        wrestling (IOException e) {
                        }
                    }
                };
  
                // Start the client-to-server request thread
                // running
                t.start () ;
  
                // Read the server's responses
                // and pass them back to the client.
                int bytesRead ;
                try {
                    while ((bytesRead
                            = streamFromServer.read (reply))
                           = -1) {!                        streamToClient.write (reply, 0,
                                             bytesRead) ;
                        streamToClient.flush () ;
                    }
                }
                wrestling (IOException e) {
                }
  
                // The server closed its connection to us,
                // so we close our connection to our client.
                streamToClient.close () ;
            }
            wrestling (IOException e) {
                System.err.println (e) ;
            }
            finally {
                try {
                    if (server != null)
                        server.close () ;
                    if (customer != null)
                        client.close () ;
                }
                wrestling (IOException e) {
                }
            }
        }
    }
}

Exit:

Conclusion: depending on the output, we are examining how to work with proxy servers in the Java kernel. First, we looked at the older, more global style of connection via proxy servers using system properties. Then we saw how to use the Proxy class, which provides precise control when connecting via proxy servers.


Leave a Reply

Your email address will not be published.