Java Reference
In-Depth Information
There are still only three kinds of proxies, HTTP, SOCKS, and direct connections (no
proxy at all), represented by three constants in the
Proxy.Type
enum:
•
Proxy.Type.DIRECT
•
Proxy.Type.HTTP
•
Proxy.Type.SOCKS
Besides its type, the other important piece of information about a proxy is its address
and port, given as a
SocketAddress
object. For example, this code fragment creates a
Proxy
object representing an HTTP proxy server on port 80 of
proxy.example.com
:
SocketAddress
address
=
new
InetSocketAddress
(
"proxy.example.com"
,
80
);
Proxy
proxy
=
new
Proxy
(
Proxy
.
Type
.
HTTP
,
address
);
Although there are only three kinds of proxy objects, there can be many proxies of the
same type for different proxy servers on different hosts.
The ProxySelector Class
Each running virtual machine has a single
java.net.ProxySelector
object it uses to
locate the proxy server for different connections. The default
ProxySelector
merely
inspects the various system properties and the URL's protocol to decide how to connect
to different hosts. However, you can install your own subclass of
ProxySelector
in place
of the default selector and use it to choose different proxies based on protocol, host,
path, time of day, or other criteria.
The key to this class is the abstract
select()
method:
public
abstract
List
<
Proxy
>
select
(
URI
uri
)
Java passes this method a
URI
object (not a
URL
object) representing the host to which
a connection is needed. For a connection made with the URL class, this object typically
has the form
http://www.example.com/
or
ftp://ftp.example.com/pub/files/
, for example.
For a pure TCP connection made with the
Socket
class, this URI will have the form
socket://host:port
:, for instance,
socket://www.example.com:80
. The
ProxySelector
ob‐
ject then chooses the right proxies for this type of object and returns them in a
List<Proxy>
.
The second abstract method in this class you must implement is
connectFailed()
:
public
void
connectFailed
(
URI
uri
,
SocketAddress
address
,
IOException
ex
)
This is a callback method used to warn a program that the proxy server isn't actually
making the connection.
Example 5-9
demonstrates with a
ProxySelector
that attempts
to use the proxy server at
proxy.example.com
for all HTTP connections unless the proxy
server has previously failed to resolve a connection to a particular URL. In that case, it
suggests a direct connection instead.