O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required