My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for


This is not the latest version.
To see the latest version,
go to GWT Developer's Guide (latest)

DevGuideHttpRequests  
Use the RequestBuilder and other classes in the com.google.gwt.http.client package to build and send HTTP requests.
Updated Feb 4, 2010 by zundel@google.com

Making HTTP requests

GWT contains a set of HTTP client classes that allow your application to make generic HTTP requests.

Using HTTP in GWT

Making HTTP requests in GWT works much like it does in any language or framework, but there are a couple of important differences you should be aware of.

First, because of the single-threaded execution model of most web browsers, long synchronous operations such as server calls can cause a JavaScript application's interface (and sometimes the browser itself) to become unresponsive. To prevent network or server communication problems from making the browser "hang", GWT allows only asynchronous server calls. When sending an HTTP request, the client code must register a callback method that will handle the response (or the error, if the call fails). For more information about the exclusion of synchronous server connections, you may want to check out this FAQ article.

Second, because GWT applications run as JavaScript within a web page, they are subject to the browser's same origin policy (SOP). SOP prevents client-side JavaScript code from interacting with untrusted (and potentially harmful) resources loaded from other websites. In particular, SOP makes it difficult (although not impossible) to send HTTP requests to servers other than the one that hosts your GWT application. This FAQ article goes into more detail about SOP and its implication for GWT developers. To see an example of SOP in action (and to learn how to work around it), check out the JSON/HTTP chapter in the Getting Started guide.

HTTP client types

To use the HTTP types in your application, you'll need to first inherit the GWT HTTP module by adding the following <inherits> tag to your module XML file:

<inherits name="com.google.gwt.http.HTTP" />

RequestBuilder is the core class you'll need for constructing and sending HTTP requests. Its constructor has parameters for specifying the HTTP method of the request (GET, POST, etc.) and the URL (the URL utility class is handy for escaping invalid characters). Once you have a RequestBuilder object, you can use its methods to set the username, password, and timeout interval. You can also set any number of headers in the HTTP request.

Once the HTTP request is ready, call the server using the sendRequest(String, RequestCallback) method. The RequestCallback argument you pass will handle the response or the error that results. When a request completely normally, your onResponseReceived(Request, Response) method is invoked. Details of the response (for example, status code, HTTP headers, and response text) can be retrieved from the Response argument. Note that the onResponseReceived(Request, Response) method is called even if the HTTP status code is something other than 200 (success). If the call does not complete normally, the onError(Request, Throwable) method gets called, with the second parameter describing the type error that occurred.

As noted before, all HTTP calls in GWT are asynchronous, so the code following the call to sendRequest(String, RequestCallback) will be executed immediately, not after the server responds to the HTTP request. You can use the Request object that is returned from sendRequest(String, RequestCallback) to monitor the status of the call, and cancel it if necessary.

Here's a brief example of making an HTTP request to a server:

import com.google.gwt.http.client.*;
...

String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

try {
  Request request = builder.sendRequest(null, new RequestCallback() {
    public void onError(Request request, Throwable exception) {
       // Couldn't connect to server (could be timeout, SOP violation, etc.)     
    }

    public void onResponseReceived(Request request, Response response) {
      if (200 == response.getStatusCode()) {
          // Process the response in response.getText()
      } else {
        // Handle the error.  Can get the status text from response.getStatusText()
      }
    }       
  });
} catch (RequestException e) {
  // Couldn't connect to server        
}

For a complete example of using the HTTP client classes, see the JSON/HTTP section in the Getting Started guide.

Processing the response

Once you receive the response from the server using Response.getText(), it's up to you to process it. If your response is encoded in JSON or XML, you can take advantage of GWT's built-in types to parse the data (see the topics Working with JSON and Working with XML, respectively).

Comment by nat...@webservicesmanagement.com, May 9, 2011

To get this to work, I had to add the following line of code to the page being requested:

For VB.Net - Response.AddHeader("Access-Control-Allow-Origin","*")

PHP equivalent - header("Access-Control-Allow-Origin: *");

W3C page on the subject is here - http://www.w3.org/TR/cors/
Comment by jzaman...@gmail.com, Jul 14, 2011

same here ... in Java, same as VB.NET above ... response.addHeader("Access-Control-Allow-Origin","*")

Comment by suga.hon...@gmail.com, Nov 26, 2011

i've tried adding the header but i still get a response status code of 0, can anyone suggest a reason why?

Comment by gary.j.k...@gmail.com, Dec 11, 2011

i am also getting response status code of 0. Something seems to be wrong with the response, the service is called ok, although without the requested data. My service is implemented with HttpServlet?.

Comment by gary.j.k...@gmail.com, Dec 11, 2011

i found that the problem was a little silly, my remote service was running on localhost:8888 whilst the gwt debugging was starting at 127.0.0.1, that seemed to be enough to cause problem, even though localhost resolved to 127.0.0.1

Comment by icydrag...@gmail.com, Dec 18, 2011

I had the similar problem. I added the header, "Access-Control-Allow-Origin: " in the server side response, all works well now.


Sign in to add a comment
Powered by Google Project Hosting