Java Reference
In-Depth Information
System . out . println ( "Content-Type: " +
response . getEntity (). getContentType (). getValue ());
BufferedReader reader = new
InputStreamReader ( response . getEntity ()
. getInputStream ()));
new BufferedReader ( new
String line = reader . readLine ();
while ( line != null
null ) {
System . out . println ( line );
line = reader . readLine ();
client . getConnectionManager (). shutdown ();
In Apache HttpClient 4.x, the org.apache.http.impl.client.DefaultHttpClient class
is responsible for managing HTTP connections. It handles the default authentication settings,
and pools and manages persistent HTTP connections (keepalive) and any other default con-
figuration settings. It is also responsible for executing requests. The
org.apache.http.client.methods.HttpGet class is used to build an actual HTTP GET
request. You initialize it with a URL and set any request headers you want using the Ht-
tpGet.addHeader() method. There are similar classes in this package for doing POST,
PUT, and DELETE invocations. Once you have built your request, you execute it by calling
DefaultHttpClient.execute() , passing in the request you built. This returns an
org.apache.http.HttpResponse object. To get the response code from this object, execute
HttpResponse.getStatusLine().getStatusCode() . The HttpResponse.getEntity()
method returns an org.apache.http.HttpEntity object, which represents the message
body of the response. From it, you can get the Content-Type by executing Ht-
tpEntity.getContentType() as well as a so you can read the re-
sponse. When you are done invoking requests, you clean up your connections by calling Ht-
tpClient.getConnectionManager().shutdown() .
To push data to the server via a POST or PUT operation, you need to encapsulate your data
within an instance of the org.apache.http.HttpEntity interface. The framework has
some simple prebuilt ones for sending strings, forms, byte arrays, and input streams. Let's
look at sending some XML.
In this example, we want to create a customer in a RESTful customer database. The API
works by POSTing an XML representation of the new customer to a specific URI. A suc-
Search WWH ::

Custom Search