I'm currently working on project involving a J2ME client on a mobile phone connecting to a Rails RESTful web service. As you might know, a RESTful web services utilizes the four HTTP verbs GET, POST, PUT and DELETE.

So yesterday we started to write unit tests, running on a J2ME device, which test if the Rails web service conforms to our specification, then suddenly we got this:

IOException: "unsupported method: PUT"

Huh?

We had the web service specification finished, the Rails Application was nearly finished, the J2ME web service adapter was finished, the J2ME GUI was underway - over 500 hours of work and suddenly this!

You can imagine our faces as we looked at the screen, reading the exception on the tiny display of the Nokia mobile phone emulator.

We went to the Sun site to get the sources of the J2ME MIDP2.0 reference implementation and found this:

public void setRequestMethod(String method) throws IOException {
    if (!method.equals(HEAD) && 
        !method.equals(GET) && 
        !method.equals(POST)) {
        throw new IOException("unsupported method: " + method);
    }
    this.method = method;
}

Why the hell did they do that? Why are they restricting the HTTP verbs to HEAD, GET and POST? Security? Fun?

To our luck, there is also another widely deployed platform/application that only supports GET and POST: the browser!

So when Rails started to support RESTful controllers and routing, they had to invent a mechanism to piggy-back PUT and DELETE requests on the POST method.

Rails solves this by using a hidden field in HTML forms named _method, but you can also specify _method as an URL parameter (given that you send a POST request):

http://localhost:3000/submarks/1?_method=put

Rails certainly intended this for the browser, but it also works with XML requests if you specify the method as URL parameter and can save your life if you use J2ME - at least it saved us from a serious headache.

Thank you Rails! And to you J2ME guys: please, remove those five idiotic lines - there are more verbs than those three.

1 Response to “J2ME and RESTful Web Service”

  1. Emilio Blanco Says:
    Hi Philipp! i'm trying to do an app that posts records to rails from J2ME, but i only get empty records when i Post from the java app, do you know where can i look or do you know how to post xml files from java to rails? i open the connection con = Connector.open("http://localhost:3000/visitas.xml", Connector.READ_WRITE) then setrequestmethod POST then setrequestproperty content-type text/xml then con.openDataOutputStream and then i use write(string.getbytes()) then i flush. i'll apriciate your help!

Leave a Reply