Wednesday, November 3, 2010

How to write a client to access Google App Engine with GWT

This tip is needed when you create a new Google App Engine project using Eclipse and choose the default settings, in particular when you leave Google Web Toolkit box checked (no trick needed if you uncheck it). If you always uncheck Google Web Toolkit you won't need this. You may still find useful the below example on how to access Google App Engine from a C# client.

The problem is that the framework will create for you all the skeletons for accessing the App Engine from the browser. But what if in addition you want to access the App Engine from a custom made client?

Passing regular parameters will not help - they won't be parsed correctly by the Google App Engine framework.
You need a custom parameter passed, that looks like this:

"5|0|6|http://1.latest.myapp.appspot.com/myapp/|SOMEGUID|myapp.clientGreetingService|greetServer|java.lang.String/2004016611|ThisIsAParameterValue|1|2|3|4|1|5|6|";


Here is the client in C# accessing Google App Engine (created from Eclipse with Web Toolkit option): 

WebRequest request = WebRequest.Create(   "http://1.latest.myapp.appspot.com/appname/greet");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "text/x-gwt-rpc; charset=utf-8";

string content = "5|0|6|http://1.latest.myapp.appspot.com/myapp/|AF76B9CA2759BDA4DBA207D5542054B2|myapp.clientGreetingService|greetServer|java.lang.String/2004016611|ThisIsAParameterValue|1|2|3|4|1|5|6|";

byte[] contentBytes = System.Text.UTF8Encoding.UTF8.GetBytes(content);
request.ContentLength = contentBytes.Length;
using (Stream stream = request.GetRequestStream())
{
    stream.Write(contentBytes, 0, contentBytes.Length);
}

WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);

reader.Close();
response.Close(); 

In a nutshell, what is important is to provide the servlet name (greet server as in the example above) and then parameter types and values. Other values are not important, the Google App Engine parser just needs the number and placement of pipes.

No comments:

Post a Comment