GET请求
String url = // 动态生成
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); //若url中包含无效字符(像空格等),需要进行编码
builder.setCallback(new RequestCallback() {
public void onError(Request request, Throwable exception) {
// 异常处理
}
public void onResponseReceived(Request request, Response response) {
// 根据响应状态码进行处理
if(Response.SC_OK == response.getStatusCode){
// 成功响应的处理
response.getText();
...
}
// 其它状态的处理,可选
}
});
// 发送请求
builder.send();
POST请求
String url = // 动态生成
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,URL.encode(url));
// 用post方法提交表单数据,需要设置Content-Type
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 将表单的数据转为字符串,作为RequestData设置给builder
String form = "name=aaa&age=13";
// setRequestData()必须在send()之前调用才有效
builder.setRequestData(form);
builder.setCallback(new RequestCallback() {
// 同上GET请求的实现
});
builder.send();
等效的另一种写法:
String url = // 动态生成
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,URL.encode(url));
builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
String form = "name=aaa&age=13";
builder.sendRequest(form,newRequestCallback() {
// 同上GET请求的实现
});
注意,对GET请求使用setRequestData()是无效的。
注意,用post方法提交表单数据,需要设置Content-Type
REST请求
GWT没有在api中预设除GET和POST之外的方法,但可以通过继承RequestBuilder来扩展这样的能力。
public class RestRequestBuilder extends RequestBuilder {
public static final String METHOD_GET = "GET";
public static final String METHOD_PUT = "PUT";
public static final String METHOD_POST = "POST";
public static final String METHOD_DELETE = "DELETE";
public RestRequestBuilder(String httpMethod, String url) {
super(httpMethod, url);
}
}
注意,使用REST请求之前请确保服务端的实现已对其支持。