ProxySelector select(URI) in Java

select(URI): This method is available in the java.net.ProxySelector class of Java.

Syntax:

List<Proxy> java.net.ProxySelector.select(URI uri)

This method takes one argument. This method selects all the applicable proxies based on the protocol to access the resource with and a destination address to access the resource at.

The format of the URI is defined as follows:

1. http URI for http connections.

2. https URI for https connections.

3. socket://host:port for tcp client socket connections.

Parameters: One parameter is required for this method.

uri: The URI that a connection is required to.

Returns: a List of Proxies. Each element in the List is of type Proxy; when no proxy is available, the list will contain one element of type Proxy that represents a direct connection.

Throws:

1. IllegalArgumentException - if the argument is null or if the protocol or host cannot be determined from the provided uri

Approach 1: When no exception

Java

package com.ProxySelector;

import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;

public class ProxySelectorselect {
    public static void main(String[] args) throws URISyntaxException {
        ProxySelector proxySelector = ProxySelector.getDefault();

        URI uri = new URI("http://localhost:8080");
        proxySelector.select(uri);
        System.out.println("Successfully select");
    }
}

Output:

Successfully select


Approach 2: IllegalArgumentException 

Java

package com.ProxySelector;

import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;

public class ProxySelectorselect {
    public static void main(String[] args) throws URISyntaxException {
        ProxySelector proxySelector = ProxySelector.getDefault();

        URI uri = null;
        proxySelector.select(uri);
        System.out.println("Successfully select");
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: URI can't be null. at java.base/sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:155) at com.ProxySelector.ProxySelectorselect.main(ProxySelectorselect.java:12)


Some other methods of ProxySelector class

connectFailed(URI, SocketAddress, IOException)This method is called to indicate that a connection could not be established to a proxy/socks server.

getDefault()This method gets the system-wide proxy selector.

ProxySelector.of(InetSocketAddress) This method returns a ProxySelector which uses the given proxy address for all HTTP and HTTPS requests. If the proxy is null then proxying is disabled.

select(URI)This method selects all the applicable proxies based on the protocol to access the resource with and a destination address to access the resource at.

ProxySelector.setDefault(ProxySelector)This method sets (or unsets) the system-wide proxy selector.

No comments:

Post a Comment