11.5. Retrieving Content with a Conditional GET
Problem
You need to retrieve the same content more than once, and you would like to have the server only send the content if it has changed since the last request.
Solution
Create a GetMethod
and set the
If-None-Match
and
If-Modified-Since
headers; these two headers
will instruct the server to refrain from sending content if the
content has not been altered since the last request. Example 11-1 makes three separate requests for the same URL
(http://www.apache.org), and,
because the content remains static, it is only sent in the response
body of the first request.
Example 11-1. Requesting information with a conditional GET
import
java.io.IOException;import
org.apache.commons.httpclient.Header;import
org.apache.commons.httpclient.HeaderElement;import
org.apache.commons.httpclient.HttpClient;import
org.apache.commons.httpclient.HttpException;import
org.apache.commons.httpclient.HttpMethod;import
org.apache.commons.httpclient.HttpStatus;import
org.apache.commons.httpclient.methods.GetMethod;public
class
ConditionalGetExample {public
static
void
main(String[] args)throws
HttpException, IOException { ConditionalGetExample example =new
ConditionalGetExample( ); example.start( ); } String entityTag = ""; String lastModified = "";public
void
start( )throws
HttpException, IOException { HttpClient client =new
HttpClient( ); HttpMethod method =new
GetMethod("http://www.apache.org");for
(int
i = 0; i < 3; i++ ) { setHeaders(method); ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.