Java Reference
In-Depth Information
Caching
By default,
HttpURLConnection
will cache results based on the caching response headers
turn off this feature.
Authentication
The
HttpURLConnection
class supports Basic, Digest, and Client Certificate Authentication.
Basic and Digest Authentication use the
java.net.Authenticator
API. Here's an example:
Authenticator
.
setDefault
(
new
new
Authenticator
() {
protected
protected
PasswordAuthentication
getPasswordAuthentication
() {
return
return new
new
PasswordAuthentication
(
"username, "
password
"
.
toCharArray
());
}
});
The
setDefault()
method is a static method of
Authenticator
. You pass in an
Authenticator
instance that overrides the class's
getPasswordAuthentication()
method.
You return a
java.net.PasswordAuthentication
object that encapsulates the username
and password to access your server. When you do
HttpURLConnection
invocations, authen-
tication will automatically be set up for you using either Basic or Digest, depending on what
the server requires.
The weirdest part of the API is that it is driven by the static method
setDefault()
. The
problem with this is that your
Authenticator
is set VM-wide. So, doing authenticated re-
quests in multiple threads to different servers is a bit problematic with the basic example just
shown. You can address this by using
java.lang.ThreadLocal
variables to store username
and passwords:
public
public class
class
MultiThreadedAuthenticator
MultiThreadedAuthenticator
extends
extends
Authenticator
{
private
private static
static
ThreadLocal
<
String
>
username
=
new
new
ThreadLocal
<
String
>();
private
private static
static
ThreadLocal
<
String
>
password
=
new
new
ThreadLocal
<
String
>();
public
public static
void
setThreadUsername
(
String user
) {
username
.
set
(
user
);
static
void
}
public
public static
void
setThreadPassword
(
String pwd
) {
password
.
set
(
pwd
);
static
void
}
protected
protected
PasswordAuthentication
getPasswordAuthentication
() {