Java Reference
In-Depth Information
tpPost.setEntity()
. Since we are expecting a redirection header with our response and we
do not want to be automatically redirected, we must configure the request to not do automat-
ic redirects. We do this by calling
HttpClientParams.setRedirection()
. We execute the
request the same way we did with our GET example. We get the
Location
header by calling
HttpResponse.getLastHeader()
.
Authentication
The Apache HttpClient 4.x supports Basic, Digest, and Client Certificate Authentication.
Basic and Digest Authentication are done through the
DefaultHttpCli-
ent.getCredentialsProvider().setCredentials()
method. Here's an example:
DefaultHttpClient client
=
new
new
DefaultHttpClient
();
client
.
getCredentialsProvider
().
setCredentials
(
new
new
AuthScope
(
"example.com"
,
443
),
new
new
UsernamePasswordCredentials
(
"bill"
,
"geheim"
);
);
The
org.apache.http.auth.AuthScope
class defines the server and port that you want to
associate with a username and password. The
org.apache.http.auth.UsernamePasswordCredentials
class encapsulates the username
and password into an object. You can call
setCredentials()
for every domain you need to
communicate with securely.
Apache HttpClient, by default, does not do preemptive authentication for the Basic and Di-
gest protocols, but does support it. Since the code to do this is a bit verbose, we won't cover
it in this topic.
Client Certificate authentication
Apache HttpClient also supports Client Certificate Authentication. As with
HttpsURLCon-
nection
, you have to load in a
KeyStore
that contains your client certificates. The section
java.net.URL
describes how to do this. You initialize an
org.apache.http.conn.ssl.SSLSocketFactory
with a loaded
KeyStore
and associate it
with the
DefaultHttpClient
. Here is an example of doing this:
import
import
java.io.File
java.io.File
;
import
import
java.io.FileInputStream
java.io.FileInputStream
;
import
import
java.security.KeyStore
java.security.KeyStore
;
import
import
org.apache.http.*
org.apache.http.*
;
import
import
org.apache.http.HttpResponse
org.apache.http.HttpResponse
;
import
import
org.apache.http.client.methods.*
org.apache.http.client.methods.*
;