Tuesday, May 3, 2011

gwt-dispatch and Custom Header or Basic Authentification

gwt-dispatch is an open source implementation of the command pattern, which is very well suited for use with GWT RPC.

In order to set Custom Headers in GWT you need to get the RequestBuilder instance which will perform the request under the covers for you.

There are two ways to do this:
  1. Let your Async Interface return RequestBuilder instead of void
  2. You can provide an instance of RPCRequestBuilder to your service, which will construct the RequestBuilderInstance

Using option one has the disadvantages that you have to send your request manually, thus changing the DispachAsync interface would break a lot of current applications (and introduce a lot of redundant code). So I was looking for another options.


You can downcast your service to ServiceDefTarget and set an instance of RPCRequestBuilder like this:

service = GWT.create(Dispatch.class);
((ServiceDefTarget) service).setRpcRequestBuilder(this.authenticatingRequestBuilder);


With and RPCRequestBuilder looking like this:

public class ACustomRequestBuilder extends RpcRequestBuilder {

@Override
protected RequestBuilder doCreate(String serviceEntryPoint) {
RequestBuilder requestBuilder = super.doCreate(serviceEntryPoint);
requestBuilder.setHeader("your header", "your value");
return requestBuilder;
}
}




Now you can easily control all aspects of your request.

Thanks to Robert Muntenau this is now also in the gwt-dispatch docs: http://code.google.com/docreader/#p=gwt-dispatch&s=gwt-dispatch&t=RequestBuilder