Java Reference
In-Depth Information
causes the
URLConnection
to disconnect should set this field to false. There are no such
methods in
java.net.URLConnection
, but some of its subclasses, such as
java.net.HttpURLConnection
, have
disconnect()
methods.
If you subclass
URLConnection
to write a protocol handler, you are responsible for set‐
ting
connected
to
true
when you are connected and resetting it to
false
when the
connection closes. Many methods in
java.net.URLConnection
read this variable to
determine what they can do. If it's set incorrectly, your program will have severe bugs
that are not easy to diagnose.
protected boolean allowUserInteraction
Some
URLConnection
s need to interact with a user. For example, a web browser may
need to ask for a username and password. However, many applications cannot assume
that a user is present to interact with it. For instance, a search engine robot is probably
running in the background without any user to provide a username and password. As
its name suggests, the
allowUserInteraction
field specifies whether user interaction
is allowed. It is
false
by default.
This variable is protected, but the public
getAllowUserInteraction()
method can read
its value and the public
setAllowUserInteraction()
method can change it:
public
void
setAllowUserInteraction
(
boolean
allowUserInteraction
)
public
boolean
getAllowUserInteraction
()
The value
true
indicates that user interaction is allowed;
false
indicates that there is
no user interaction. The value may be read at any time but may be set only before the
URLConnection
is connected. Calling
setAllowUserInteraction()
when the
URLConnection
is connected throws an
IllegalStateException
.
For example, this code fragment opens a connection that could ask the user for au‐
thentication if it's required:
URL
u
=
new
URL
(
"http://www.example.com/passwordProtectedPage.html"
);
URLConnection
uc
=
u
.
openConnection
();
uc
.
setAllowUserInteraction
(
true
);
InputStream
in
=
uc
.
getInputStream
();
Java does not include a default GUI for asking the user for a username and password.
If the request is made from an applet, the browser's usual authentication dialog can be
relied on. In a standalone application, you first need to install an
Authenticator
, as
discussed in
“Accessing Password-Protected Sites” on page 161
.
Figure 7-1
shows the dialog box that pops up when you try to access a password-
protected page. If you cancel this dialog, you'll get a 401 Authorization Required error
and whatever text the server sends to unauthorized users. However, if you refuse to send
authorization at all—which you can do by clicking OK, then answering No when asked