Proxy Proxy(Type, SocketAddress) in Java

Proxy(Type, SocketAddress): This method is available in the java.net.Proxy class of Java.

Syntax:

java.net.Proxy.Proxy(Type type, SocketAddress sa)

This method takes two arguments. This method creates an entry representing a PROXY connection. Certain combinations are illegal. For instance, for types Http, and socks, a SocketAddress must be provided.

Use the Proxy.NO_PROXY constant for representing a direct connection.

Parameters: Two parameters are required for this method.

type: the Type of proxy.

sa: the SocketAddress for that proxy.

Throws:

1. IllegalArgumentException - when the type and the address are incompatible

Approach 1: When no exception

Java

package com.Proxy;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class Proxy1 {
    public static void main(String[] args) throws UnknownHostException {

        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;
        SocketAddress sockaddr = new InetSocketAddress(addr, port);
        Proxy proxy = new Proxy(Type.HTTP, sockaddr);
        System.out.println(proxy);

    }
}

Output:

HTTP @ java.sun.com/23.54.83.211:80


Approach 2: IllegalArgumentException 

Java

package com.Proxy;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class Proxy1 {
    public static void main(String[] args) throws UnknownHostException {

        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;
        SocketAddress sockaddr = new InetSocketAddress(addr, port);
       
        Proxy proxy = new Proxy(Type.DIRECT, sockaddr);
        System.out.println(proxy);

    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: type DIRECT is not compatible with address java.sun.com/23.54.82.226:80 at java.base/java.net.Proxy.<init>(Proxy.java:95) at com.Proxy.Proxy1.main(Proxy1.java:17)


Some other methods of Proxy class

Proxy(Type, SocketAddress)This method creates an entry representing a PROXY connection. 

address()This method returns the socket address of the proxy, or null if it's a direct connection.

Proxy ConstantsSome of the Proxy constants like Proxy.NO_PROXY, Type.DIRECT, etc.

equals(Object)This method compares this object against the specified object.

hashCode()This method returns a hashcode for this Proxy.

toString()This method constructs a string representation of this Proxy. This String is constructed by calling toString() on its type and concatenating " @ " and the toString() results from its address if its type is not DIRECT.

type()This method returns the proxy type.

No comments:

Post a Comment