For quite a while now, I’ve been trying to figure out what one would use on a greenfield project for passing stuff back and forth to the server. There are many options. So far, in the projects we’ve worked on…
– Custom XML. That worked, but was rough.
– XML-RPC calls. Ehh.
– Json. Now I feel like we’re getting somewhere. The class definitions are pretty loose, but at least its structured data. Using it with Java can be kind of rough, as you wind up with really basic classes, but its still pretty good.
What I really want is a way to deal with real objects and classes. Structured data. You can get a custom XML message and manually inflate that, but its extra work, and when things change, you don’t know about it automatically. Worse, on some projects, there’s no real documentation on the data you’ll get back, so we’ve been surprised on many occasions.
XML-RPC and Json does a pretty good job, but you still wind up with loose data structure. OK, but whatever.
The Seam Remoting project worked fairly well for me. Its VERY specific, in that you have to be using Seam on the server to use it, and its proprietary, which is generally ALWAYS bad, but it allowed me to write some simplified TO classes, and deploy them both on the server and phone, and use that to talk back and forth with the server.
With my new project I started using my seam remoting stuff. Now, it used to work fine, but I was using jdom instead of the regular XML classes. I converted it to the standard XML stuff, and promptly ran into a number of bugs. I started fixing them. Then realized, wow, what a waste of time.
Enter protocol buffers. In a nutshell, its a google product. You write message definitions in a text file, and compile them to the language of your choice. For Java (which is all I care about today), you get structured class files, which is exactly what I want, and you can stream/inflate them right into/out of streams and byte arrays. Perfect for the interweb. I’ll let you do the research on protocol buffers if you want, or click here: http://tinyurl.com/2v9wbj5.
Implementing them on Android, and in my case, a Servlet back end, is what I’m going to talk about here. Any way you can shove a byte array up to the server and back would allow you to use protocol buffers, but some ways are better than others. In the past, we’ve wound up passing files in a multipart message, but in this case, I made the body of the message the raw byte data. I would have to check with the actual protocol. I assume its still encoded in some way, like base 64, but possibly not, which would be sweet. In any case, having a singular object made the whole thing simpler.
On the phone, here’s the code I use to call a remote servlet with PB:
public static Object callServerWithPayload(String methodName, byte data, String... params)
DefaultHttpClient client = new DefaultHttpClient();
StringBuilder sb = new StringBuilder();
sb.append(SERVER_ADDRESS + SERVLET_PATH);
for (String param : params)
HttpPost method = new HttpPost(sb.toString());
HttpResponse response = client.execute(method);
catch (Exception e)
The way I call the servlet is as follows:
“rpcproto” is just the name of the servlet. Everything after that is part of the request.
“methodName” lets the server know what you’re trying to do.
The params are optional. Some calls actually don’t need to push an object to the server, so not needing a custom message object for those makes life a lot easier.
The ‘data’ byte array was passed into this method, but would have come from the ‘writeTo’ method on the actual PB data object. Here’s an example…
BaseResult.UserTO.Builder userTO = BaseResult.UserTO.newBuilder();
BaseResult.UserTO userTOData = userTO.build();
ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
catch (IOException e)
So, build a PB object, stuff it into a byte array, send it to server. On the way back, just read from the input stream and inflate the data object:
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
BaseResult.CreateUserResult createUserResult = BaseResult.CreateUserResult.parseFrom(inputStream);
output.setText("User id: "+ createUserResult.getUser().getUserId());
By the way, the “BaseResult” object is just what I called my .proto file, “base_result.proto”. All the data objects were included inside that.
On the server. You can actually just read from the input stream and write to the output stream directly. Its all pretty simple stuff.
String split = StringUtils.split(request.getPathInfo(), "/");
String methodName = split;
MobileClient mobileClient = (MobileClient) Component.getInstance(“mobileClient”);
ServletOutputStream outputStream = response.getOutputStream();
long userId = Long.parseLong(split);
ServletInputStream inputStream = request.getInputStream();
BaseResult.UserTO userTO = BaseResult.UserTO.parseFrom(inputStream);
throw new RuntimeException(“Unknown method: ” + methodName);
The “MobileClient” thing is actually an EJB with methods for our mobile support. Don’t worry about that.
Call this code from a ‘doPost’ implementation.
Simple. Fast. Use it.
Negatives of protocol buffers are:
– Data model is simplistic. No “Map” type, missing other primitive types (Date, etc).
– Language support is fairly small. C++, Java, and Python. There are several 3rd party implementations, but that’s always a little scary.
Negatives weren’t enough to dissuade me, and so far, its working out great.