Friday, July 9, 2010

Porting Android code to Google App Engine /J

One of the advantages of working in Java on Android is much of the back-end code can be transported to Google App Engine/Java (GAE/J) without much effort. This is quite nice as one can rev/iterate/test backend code quickly on GAE/J and then move it to Android once solid. It's also nice as one can remain in the same frame of mind while coding front and backend.

In the case of Keas API code for Android, the backend is comprised mostly for API calls and XML processing. Most of the code remains consistent between Android and GAE/J, with some subtle differences in 'framing' and underlying class assumptions.

You can see the Keas API application on GAE/J here: http://keasapi.appspot.com
The Elipse project files can be found here.



Here is one example, establishing an http connection, note the differences in http class interfaces and the details of setting header data.

Http connection from within Android:

public void getData(String username, String password, String partnerId,
String namespace) {

try {
HttpGet get = new HttpGet("https://preview.keas.com/rest/api/getdata?query="+namespace);
get.setHeader(new BasicHeader("username", username));
get.setHeader(new BasicHeader("password", password));
get.setHeader(new BasicHeader("partnerId", partnerId));

HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();

BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 1024);

XmlPullParserFactory xppFact = XmlPullParserFactory.newInstance();
xppFact.setNamespaceAware(true);
XmlPullParser xpp = xppFact.newPullParser();
...


Http connection from GAE/J servlet:

private void getData(HttpServletResponse resp, String uid, String pw, String query) {

try {
URL url = new URL("https://preview.keas.com/rest/api/getdata?query="+query);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("username", uid);
connection.setRequestProperty("password", pw);
connection.setRequestProperty("partnerId", "keas.apitest");

connection.connect();
Object content=connection.getContent();


if (content instanceof InputStream || content instanceof Reader) {

XmlPullParserFactory xppFact = XmlPullParserFactory.newInstance();
xppFact.setNamespaceAware(true);
XmlPullParser xpp = xppFact.newPullParser();
...

No comments:

Post a Comment