GWT + REST sample code

88 views
Skip to first unread message

marius.andreiana

unread,
Aug 23, 2010, 3:20:13 PM8/23/10
to Google Web Toolkit
Hi all,

I've been trying various ways / libraries to get a Hello World of
using REST APIs from GWT. Turns out it's most easy with native GWT.

In case it's useful to others, here's a step by step brief tutorial,
which I would have liked to see when starting to look into this:

1. Add this line to project.gwt.xml
<inherits name="com.google.gwt.http.HTTP"/>

2. Add this code somewhere (I've used the default project created in
eclipse)
//code credit to StackOverflow
import com.google.gwt.http.client.*;
//...

public void onModuleLoad() {
//...
// http headers
final String CONTENT_TYPE_HEADER = "Content-Type";
final String ACCEPT_HEADER = "Accept";

final String CONTENT_TYPE = "application/json";


String url = "http://...";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
URL.encode(url));
builder.setHeader(CONTENT_TYPE_HEADER, CONTENT_TYPE);
builder.setHeader(ACCEPT_HEADER, CONTENT_TYPE);

String requestBody = "{\"key\": \"value\"}";

try {
Request request = builder.sendRequest(requestBody, new
RequestCallback() {
public void onError(Request request, Throwable exception)
{
System.out.println("Error1 " + exception.getMessage());
}

public void onResponseReceived(Request request, Response
response) {

System.out.println("Response " + response.getText());
System.out.println(response.getStatusCode());

if (200 == response.getStatusCode()) {
Window.alert("success " + response.getText());
} else {
Window.alert("error " + response.getText());
}
}
});
} catch (RequestException e) {
e.printStackTrace();
}

This is all.

Marius
Reply all
Reply to author
Forward
0 new messages