Java Reference
In-Depth Information
Second, the framework does not do preemptive authentication for Basic or Digest Authentic-
ation. This means that
HttpURLConnection
will first try to invoke a request without any au-
thentication headers set. If the server requires authentication, the initial request will fail with
a 401, “Unauthorized,” response code. The
HttpURLConnection
implementation then looks
at the
WWW-Authenticate
header to see whether Basic or Digest Authentication should be
used and retries the request. This can have an impact on the performance of your system be-
cause each authenticated request will actually be two requests between the client and server.
Third, the framework can't do something as simple as form parameters. All you have to work
with are
java.io.OutputStream
and
java.io.InputStream
to perform your input and out-
put.
Finally, the framework only allows you to invoke the HTTP methods GET, POST, DELETE,
PUT, TRACE, OPTIONS, and HEAD. If you try to invoke any HTTP method other than
those, an exception is thrown and your invocation will abort. In general, this is not that im-
portant unless you want to invoke newer HTTP methods like those defined in the WebDAV
specification.
Apache HttpClient
The Apache foundation has written a nice, extensible, HTTP client library called HttpCli-
RS-aware, it does have facilities for preemptive authentication and APIs for dealing with a
few different media types like forms and multipart. Some of its other features are a full inter-
ceptor model, automatic cookie handling between requests, and pluggable authentication.
Let's look at a simple example:
import
import
org.apache.http.*
org.apache.http.*
;
import
import
org.apache.http.client.*
org.apache.http.client.*
;
public
public class
class
MyClient
MyClient
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
DefaultHttpClient client
=
new
new
DefaultHttpClient
();
HttpGet get
=
new
new
HttpGet
(
"http://example.com/customers/1"
);
get
.
addHeader
(
"accept"
,
"application/xml"
);
HttpResponse response
=
client
.
execute
(
get
);
iif
(
response
.
getStatusLine
().
getStatusCode
() !=
200
) {
throw
throw new
new
RuntimeException
(
"Operation failed: "
+
response
.
getStatusLine
().
getStatusCode
());
}