Java Reference
In-Depth Information
Example 5-9. A ProxySelector that remembers what it can connect to
import
java.io.*
;
import
java.net.*
;
import
java.util.*
;
public
class
LocalProxySelector
extends
ProxySelector
{
private
List
<
URI
>
failed
=
new
ArrayList
<
URI
>();
public
List
<
Proxy
>
select
(
URI
uri
)
{
List
<
Proxy
>
result
=
new
ArrayList
<
Proxy
>();
if
(
failed
.
contains
(
uri
)
||
!
"http"
.
equalsIgnoreCase
(
uri
.
getScheme
()))
{
result
.
add
(
Proxy
.
NO_PROXY
);
}
else
{
SocketAddress
proxyAddress
=
new
InetSocketAddress
(
"proxy.example.com"
,
8000
);
Proxy
proxy
=
new
Proxy
(
Proxy
.
Type
.
HTTP
,
proxyAddress
);
result
.
add
(
proxy
);
}
return
result
;
}
public
void
connectFailed
(
URI
uri
,
SocketAddress
address
,
IOException
ex
)
{
failed
.
add
(
uri
);
}
}
As I said, each virtual machine has exactly one
ProxySelector
. To change the
Proxy
Selector
, pass the new selector to the static
ProxySelector.setDefault()
method,
like so:
ProxySelector
selector
=
new
LocalProxySelector
():
ProxySelector
.
setDefault
(
selector
);
From this point forward, all connections opened by that virtual machine will ask the
ProxySelector
for the right proxy to use. You normally shouldn't use this in code run‐
ning in a shared environment. For instance, you wouldn't change the
ProxySelector
in a servlet because that would change the
ProxySelector
for all servlets running in the
same container.
Communicating with Server-Side Programs Through GET
The
URL
class makes it easy for Java applets and applications to communicate with server-
side programs such as CGIs, servlets, PHP pages, and others that use the
GET
method.
(Server-side programs that use the
POST
method require the
URLConnection
class and