Using Google App Engine as Backend for Android

December 2nd, 2011 · No Comments

If you’re looking for a way to create a backend for your Android application, Google App Engine looks like the perfect choice: You can use Java as you can do for Android and you don’t need to think too much about hosting, as it is all stored in the cloud.

Another benefit is that you can reuse your transfer objects on the client and on server side. But as it is often there are some problems doing this in practice. So you don’t have the same ones I had, I am glad to share my experiences with you.

So first question is what libraries are to use for the client/server communication. At start I tried Restlet 2.0. Looked like a great choice as there are special editions for App Engine and for Android available. In practice it is not very useful as the libraries are to big for Android and I also very much disliked that fully serialized java objects are transfered.

Best approach I found so far is to use Jersey 1.6: It is easy to use and implements the JAX-RS (JSR 311) standard. To set it up on the App Engine, please consult these blog posts from me: Using real POJOs (without JAXB Annotations) as transfer objects with JAX-RS and Storing large images RESTful in the cloud using Google App Engine.

Ok, so far about the server side. To keep things small and simple on the Android side, I mainly created the following wrapper class for the HttpClient to handle the HTTP requests:

import org.codehaus.jackson.map.ObjectMapper;
 
public class HttpUtils {
 
        private static final int SERVER_PORT = 80;
        private static final String SERVER_IP = "myapp.appspot.com"; // use 10.0.2.2 for emulator
 
        private static HttpUtils instance = new HttpUtils();
        private DefaultHttpClient client;
        private ResponseHandler<String> responseHandler;
        private ObjectMapper mapper;
 
        private HttpUtils() {
                super();
                client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000);
                responseHandler = new BasicResponseHandler();
                mapper = new ObjectMapper(); // can reuse, share globally
        }
 
        public static HttpUtils getInstance() {
                return instance;
        }
 
        public String doGet(String path) throws IOException {
                return doGet(path, null);
        }
 
        public String doGet(String path, String query) throws IOException {
                try {
                        URI uri;
                        uri = createURI(path, query);
                        HttpGet get = new HttpGet(uri);
                        HttpResponse response = client.execute(get);
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == HttpStatus.SC_OK) {
                                return responseHandler.handleResponse(response);
                        } else {
                                throw new IOException("wrong http status: " + statusCode);
                        }
                } catch (URISyntaxException e) {
                        throw new IOException("uri syntax error");
                } catch (ClientProtocolException e) {
                        throw new IOException("protocol error");
                } 
 
        }
 
        private URI createURI(String path, String query) throws URISyntaxException {
                return URIUtils.createURI("http", SERVER_IP, SERVER_PORT, "rest/" + path, query, null);
        }
 
        public boolean doPut(String path, Object object) throws IOException {
                try {
                        String json = mapper.writeValueAsString(object);
                        URI uri = createURI(path, null);
                        HttpPut put = new HttpPut(uri);
                        put.addHeader("Accept", "application/json");
                        put.addHeader("Content-Type", "application/json");
                        StringEntity entity = new StringEntity(json, "UTF-8");
                        entity.setContentType("application/json");
                        put.setEntity(entity);
                        HttpResponse response = client.execute(put);
                        int statusCode = response.getStatusLine().getStatusCode();
                        return statusCode == HttpStatus.SC_OK;
                } catch (URISyntaxException e) {
                        throw new IOException("uri syntax error");
                } catch (ClientProtocolException e) {
                        throw new IOException("protocol error");
                }
        }
 
        public String doPutFile(final String path, final File file) throws URISyntaxException, HttpException,
                        IOException {
                URI uri = createURI(path, null);
                HttpPut put = new HttpPut(uri);
                String mimeType = "binary/octet-stream";
                if(file.getName().matches(".*\\.(jpeg|jpg)"))
                        mimeType = "image/jpeg";
                FileEntity reqEntity = new FileEntity(file, mimeType);
                put.setEntity(reqEntity);
                HttpResponse response = client.execute(put);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                        return responseHandler.handleResponse(response);
                } else {
                        throw new IOException("wrong http status: " + statusCode);
                }
        }
 
        public String doPost(final String path, final String POSTText) throws URISyntaxException, HttpException,
                        IOException {
                URI uri = createURI(path, null);
                HttpPost httpPost = new HttpPost(uri);
                StringEntity entity = new StringEntity(POSTText, "UTF-8");
                BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE, "application/json");
                httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                entity.setContentType(basicHeader);
                httpPost.setEntity(entity);
                HttpResponse response = client.execute(httpPost);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                        return responseHandler.handleResponse(response);
                } else {
                        throw new IOException("wrong http status: " + statusCode);
                }
        }
 
        public boolean doDelete(final String path) throws HttpException, IOException, URISyntaxException {
                URI uri = createURI(path, null);
                HttpDelete httpDelete = new HttpDelete(uri);
                httpDelete.addHeader("Accept", "text/html, image/jpeg, *; q=.2, */*; q=.2");
                HttpResponse response = client.execute(httpDelete);
                int statusCode = response.getStatusLine().getStatusCode();
                return statusCode == HttpStatus.SC_OK ? true : false;
        }
 
}

This implementation is far from perfect, especially exception handling and passing parameters need to be improved, but it works so far :)

Using this class it is easy to store a file using the FileServerResource from my former blog post. Just call:

File imageFile = new File(new URI(myimgage.getImageURL()));
String url = HttpUtils.getInstance().doPutFile("file/store", imageFile);

Also it is easy to store a transfer object using the doPut method. Note that is is using the ObjectMapper class from Jackson, the same JSON processor that is also used by Jersey.
Jackson is therefore the only additional library that you need on the Android side which keeps the executable small. If you use the same version of Jackson on the client side as on the server side you’re also ensured that the (un-)marshalling process of your transfer objects works flawlessly on both sides.

Hope you liked this approach – feel free to discuss here further ideas.

Topics: · , , ,

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment