java.net.Proxy Class in Java
Last Updated :
16 Jun, 2022
A proxy is an immutable object and type of tool or application or program or system, which helps to protect the information of its users and computers. It acts as a barrier between computer and internet users. A Proxy Object defines the Proxy settings to be used with a connection. Proxy servers are already pre-installed in Windows in a type of program or application. It is automatically saved in the settings section. You can also make customs for which site you want to use a proxy. InetSocketAddress class from java.net package implements IP socket address(combination of IP address and port number). The objects of this class are immutable and can be used for binding, connecting purposes
The java.net.Proxy class represents a proxy setting which is basically a type and a socket address. The class contains a special field that is the no proxy field. It is written as Proxy NO_PROXY; this setting tells the protocol handler not to use any proxy setting and represents a Direct connection.
Syntax: Class Declaration
public class Proxy extends Object
Let us do discuss the constructor of this class prior to jumping onto the methods
Proxy(Proxy.Type type, SocketAddress sa)
Methods of the class are as follows
Method Name |
Description |
address() |
Returns the socket address of the proxy or returns null for a direct connection. |
equals() |
Compares both the proxy objects and returns true only if the type and address are same. |
hashCode() |
Returns a hashcode for the proxy. |
toString() |
Returns a string representation of the proxy. |
type() |
Returns the type of the proxy object. |
Approach:
- First, we have created a Socket Address in order to use with the proxy object.
- Then created a HTTP type proxy with that address.
- Then we have created a URL connection with the proxy we created.
Implementation:
Example
Java
import java.io.*;
import java.net.*;
import java.net.Proxy;
public class GFG {
public static void main(String[] args)
{
SocketAddress addr = new InetSocketAddress(
"webcache.example.com" , 8080 );
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
try {
URLConnection conn = url.openConnection(proxy);
}
catch (Exception e) {
e.printStackTrace();
System.out.println( false );
}
System.out.println( "Proxy Type: " + proxy.type());
System.out.println( "Proxy Address: "
+ proxy.address());
System.out.println( "Proxy HasHCode: "
+ proxy.hashCode());
System.out.println( "Proxy String: "
+ proxy.toString());
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...