Hi everyone,
What would be the best way to consume a REST service in a J2ME/Java ME application? Data is in JSON format. Unfortunately there don't seem to be any helper libraries available.
Many thanks
Hi everyone,
What would be the best way to consume a REST service in a J2ME/Java ME application? Data is in JSON format. Unfortunately there don't seem to be any helper libraries available.
Many thanks
Hello Infms !
I am using https://github.com/upictec/org.json.me/, with success, for a REST/JSON service.
The usage is straightforward, just download the buffer and decode it using json parser.
Code:// downloading .... public boolean Response20X(HttpConnection connection, Hashtable cookies) { boolean result = false; StringBuffer strf = null; response = null; try { InputStream is = connection.openInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); int ch; strf = new StringBuffer(); while ((ch = isr.read()) != -1) { strf.append((char) ch); } response = strf.toString(); strf = null; // TODO do not decode before checking reponse code result = data.fromJSONString(response); response = null; isr.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } return result; }Marcelo BarrosCode:// decoding .... public boolean fromJSONString(String str) { boolean result = false; try { Vector _data = new Vector(); JSONObject jobj = new JSONObject(str); JSONArray feeds = jobj.getJSONArray("data"); if(feeds != null) { for(int n = 0 ; n < feeds.length(); n++) { // more decoding ... } } result = true; } catch (JSONException ex) { ex.printStackTrace(); } return result; }
Hi Marcelo,
Thanks for the reply and example code. Say for example I had a REST service I wanted to access at htt://alpha.myrestservice.com/ and send the request: GET api/lists
How would I go about using the library to send such a request?
Thanks
The request should be done via some HttpConnection call. For instance:
Check the demo "PicasaViewer" for another example: http://is.gd/JmLsV8Code:String url = "https://api.instagram.com/v1/users/self/feed"; HttpConnection connection = (HttpConnection) Connector.open(url,Connector.READ_WRITE,true); connection.setRequestMethod(HttpConnection.GET); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Series40)"); connection.setRequestProperty("Connection", "close"); int code = connection.getResponseCode(); if(code == HttpConnection.HTTP_OK) { // handle result, read data ... } else { /// ... } connection.close();
See you
Marcelo Barros
Moreover, have you tried Tantalum ? It seems pretty good.
https://projects.developer.nokia.com/Tantalum
"Simplified XML and JSON parsing into value objects"
We will give it a try ASAP.
Marcelo Barros
I ended up using the Tantalum library (for handling JSON) along with the HttpConnection GET request, similar to what you posted below. Everything works great! Thanks again