Package com.google.gwt.http.client


package com.google.gwt.http.client
Provides the client-side classes and interfaces for making HTTP requests and processing the associated responses.

Most applications will be interested in the Request, RequestBuilder, RequestCallback and Response classes.

Caveats

Same-Origin Security Policy

Modern web browsers restrict client-side scripts from accessing items outside of their source origin. This means that a script loaded from www.foo.com cannot access content from www.bar.com. For more details please see, Same-Origin Security Policy.

Pending Request Limit

Modern web browsers are limited to having only two HTTP requests outstanding at any one time. If your server experiences an error that prevents it from sending a response, it can tie up your outstanding requests. If you are concerned about this, you can always set timeouts for the request via RequestBuilder.setTimeoutMillis(int).

Required Module

Modules that use the classes and interfaces in this package should inherit the com.google.gwt.http.HTTP module.
<module>
  <!-- other inherited modules, such as com.google.gwt.user.User -->
  <inherits name="com.google.gwt.http.HTTP"/>
  <!-- additional module settings -->
</module>

Quick Howto's

How should I write a RequestCallback handler class?

The following code shows how a RequestCallback instance should be written.
public class RequestCallbackExample implements RequestCallback {

  private static final int STATUS_CODE_OK = 200;

  public void onError(Request request, Throwable exception) {
    if (exception instanceof RequestTimeoutException) {
      // handle a request timeout
    } else {
      // handle other request errors
    }
  }

  public void onResponseReceived(Request request, Response response) {
    if (STATUS_CODE_OK == response.getStatusCode()) {
      // handle OK response from the server 
    } else {
      // handle non-OK response from the server
    }
  }
}

How do I make a GET request?

The following example demonstrates how to perform an HTTP GET request.
public class GetExample implements EntryPoint {
  public static final int STATUS_CODE_OK = 200;
  
  public static void doGet(String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
      Request response = builder.sendRequest(null, new RequestCallback() {
        public void onError(Request request, Throwable exception) {
          // Code omitted for clarity
        }

        public void onResponseReceived(Request request, Response response) {
          // Code omitted for clarity
        }
      });
    } catch (RequestException e) {
      // Code omitted for clarity
    }
  }

  public void onModuleLoad() {
    doGet("/");
  }
}

How do I make a POST request?

The following example demonstrates how to perform an HTTP POST request.
public class PostExample {
  public static void doPost(String url, String postData) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

    try {
      builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
      Request response = builder.sendRequest(postData, new RequestCallback() {

        public void onError(Request request, Throwable exception) {
          // code omitted for clarity
        }

        public void onResponseReceived(Request request, Response response) {
          // code omitted for clarity
        }
      });
    } catch (RequestException e) {
      Window.alert("Failed to send the request: " + e.getMessage());
    }
  }

  public void onModuleLoad() {
    doPost("/", "Hello World!");
  }
}

How do I use request timeouts?

The following example demonstrates how to use the timeout feature.
public class TimeoutExample implements EntryPoint {
  public static void doGetWithTimeout(String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
      /*
       * wait 2000 milliseconds for the request to complete
       */
      builder.setTimeoutMillis(2000);
      
      Request response = builder.sendRequest(null, new RequestCallback() {
        public void onError(Request request, Throwable exception) {
          if (exception instanceof RequestTimeoutException) {
            // handle a request timeout
          } else {
            // handle other request errors
          }
        }

        public void onResponseReceived(Request request, Response response) {
          // code omitted for clarity
        }
      });
    } catch (RequestException e) {
      Window.alert("Failed to send the request: " + e.getMessage());
    }
  }

  public void onModuleLoad() {
    doGetWithTimeout("/");
  }
}

How do I construct a string for use in a query or POST body?

The following example demonstrates how to build a x-www-form-urlencoded string that can be used as a query string or as the body of a POST request.
public class QueryAndFormDataExample {
  
  public static interface Entry {
    String getName();
    String getValue();
  }

  public static String buildQueryString(Entry[] queryEntries) {
    StringBuffer sb = new StringBuffer();

    for (int i = 0, n = queryEntries.length; i < n; ++i) {
      Entry queryEntry = queryEntries[i];

      if (i > 0) {
        sb.append("&");
      }

      // encode the characters in the name
      String encodedName = URL.encodeQueryString(queryEntry.getName());
      sb.append(encodedName);
      
      sb.append("=");
    
      // encode the characters in the value
      String encodedValue = URL.encodeQueryString(queryEntry.getValue());
      sb.append(encodedValue);
    }
    
    return sb.toString();
  }
}

How can I make a RequestBuilder send a request other than GET or POST?

The following example demonstrates how to allow an HTTP request other than a GET or a POST to be made. Beware: if you plan on supporting Safari, you cannot use this scheme.
public class RequestBuilderForAnyHTTPMethodTypeExample extends RequestBuilder {
  
  /**
   * Constructor that allows a developer to override the HTTP method 
   * restrictions imposed by the RequestBuilder class.  Note if you override the 
   * RequestBuilder's HTTP method restrictions in this manner, your application 
   * may not work correctly on Safari browsers.
   * 
   * @param httpMethod any non-null, non-empty string is considered valid
   * @param url any non-null, non-empty string is considered valid
   *
   * @throws IllegalArgumentException if httpMethod or url are empty
   * @throws NullPointerException if httpMethod or url are null
   */
  public RequestBuilderForAnyHTTPMethodTypeExample(String httpMethod, String url) {
    super(httpMethod, url);
  }
}