November 2004
Intermediate to advanced
400 pages
10h 31m
English
You need to retrieve information with the HTTP GET method.
Create an instance of HttpClient and use it to
execute a GetMethod
object.
Once the method has been executed, the response body can be accessed
as an InputStream, byte[], or
String. The following example gets the contents of
http://www.discursive.com/jccook/
and retrieves the response body as a string:
importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.HttpException;importorg.apache.commons.httpclient.HttpMethod;importorg.apache.commons.httpclient.methods.GetMethod; HttpClient client =newHttpClient( ); String url = "http://www.discursive.com/jccook/"; HttpMethod method =newGetMethod( url );try{ client.executeMethod( method ); if( method.getStatusCode( ) == HttpStatus.SC_OK ) { String response = method.getResponseBodyAsString( ); System.out.println( response ); } }catch( HttpException he ) { System.out.println( "HTTP Problem: " + he.getMessage( ) ); }catch( IOException ioe ) { System.out.println( "IO Exeception: " + ioe.getMessage( ) ); }finally{ method.releaseConnection( ); method.recycle( ); }
This code retrieves the content of http://www.discursive.com/jccook using the
HTTP GET method. If the response code is
HttpStatus.SC_OK or 200, the
response is printed to the console:
<html> <head> <title>JCCook Example</title> </head> <body> <h1>Hello World!</h1> </body> </html>
Note the exception handling involved in this example. ...
Read now
Unlock full access