Java Reference
In-Depth Information
This application connects to the testing address and outputs all server-sent headers
and its response code. After compiling the source code ( javac
BasicAuthNeeded.java ),runtheapplication( java BasicAuthNeeded ).You
should see output that is similar to the following:
null: HTTP/1.1 401 Authorization Required
WWW-Authenticate: Basic realm="basic auth area"
Date: Mon, 19 Sep 2011 03:06:06 GMT
Content-Length: 401
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
Server: Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.3.2
401
The WWW-Authenticate header's realm attributereveals basic auth area
as the realm. Although not shown, any username from user1 through user9 and a
password that's the same as the username can be specified to authenticate.
InordertopassthisusernameandpasswordbacktotheHTTPserver,theapplication
must work with the java.net.Authenticator class, as Listing 9-15 demon-
strates.
Listing 9-15. Performing basic authentication
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
class BasicAuthGiven
{
final static String USERNAME = "user1";
Search WWH ::




Custom Search