RESTclient for Blackberry

Recently, I’ve ventured out into the Blackberry app development space and found that some documentation is lacking for developers to create awesome applications for that platform. After searching around Google, Stack Overflow, and RIM’s developer zone, I came to the conclusion that there isn’t any good examples of how to implement a REST client effectively in a Blackberry Java-based environment.

REST clients are a mobile app developers best friend. They allow developers to make lightweight network calls to useful APIs such as the Graph API, Twitter’s API, and Google’s family of APIs including Maps, Google+, and Youtube. I came across a great example, RESTclient for Android by Tyler Smith, and used this implementation to create a foundation for a Blackberry REST client.

Introducing RESTclient for Blackberry with basic authentication and JSON body posting (notice that this implementation only utilizes the REST verbs GET and POST):

public class RestClient {
private String _url;

private Vector _headers;
private Vector _params;

private String _json;

private int _response_code;
private String _response;

private boolean _authentication = false;
private String _username;
private String _password;

public RestClient() {
_url = null;

_headers = new Vector();
_params = new Vector();
}

public RestClient(String url) {
_url = url;

_headers = new Vector();
_params = new Vector();
}

public void addBasicAuth(String username, String password) {
_authentication = true;

_username = username;
_password = password;
}

public void addHeader(String name, String value) {
_headers.addElement(new NameValuePair(name, value));
}

public void addParam(String name, String value) {
_params.addElement(new NameValuePair(name, value));
}

public void execute(int method) throws Exception {
switch(method) {
case RestMethod.GET: {
HttpsConnection request = (HttpsConnection) Connector.open(_url + addGetParams());
request.setRequestMethod(HttpConnection.GET);
addHeaderParams(request);

executeRequest(request);
break;
}
case RestMethod.POST: {
HttpsConnection request = (HttpsConnection) Connector.open(_url);
request.setRequestMethod(HttpConnection.POST);
addHeaderParams(request);
addBodyParams(request);

executeRequest(request);
break;
}
}
}

private void addHeaderParams(HttpsConnection request) throws Exception {
for(int i = 0; i < _headers.size(); i++) {
request.setRequestProperty(((NameValuePair) _headers.elementAt(i)).getName(), ((NameValuePair) _headers.elementAt(i)).getValue());
}

if(_authentication) {
byte[] cred = Base64OutputStream.encode((_username + ":" + _password).getBytes("UTF-8"), 0, (_username + ":" + _password).length(), false, false);

request.setRequestProperty("Authorization", "Basic " + new String(cred).toString());
}
}

private void addBodyParams(HttpsConnection request) throws Exception {
if(_json != null) {
byte[] data = _json.getBytes("UTF-8");

request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Content-Length", String.valueOf(data.length));

OutputStream os = request.openDataOutputStream();

os.write(data);
os.flush();
os.close();
}
}

private String addGetParams() throws Exception {
StringBuffer buff = new StringBuffer();
if(!_params.isEmpty()) {
buff.append("?");

for(int i = 0; i < _params.size(); i++) {
buff.append(_params.size() > 1 ? "&" : "" + ((NameValuePair) _params.elementAt(i)).getName() + ((NameValuePair) _params.elementAt(i)).getValue());
}
}

return buff.toString();
}

public int getResponseCode() {
return _response_code;
}

public String getResponse() {
return _response;
}

public void setURL(String url) {
_url = url;
}

public void setJSONString(String json) {
_json = json;
}

private void executeRequest(HttpsConnection request) {
try {
_response_code = request.getResponseCode();

if(_response_code == HttpsConnection.HTTP_OK) {
InputStream is = request.openInputStream();

int len = (int) request.getLength();
if(len > 0) {
int actual = 0;
int read = 0;
byte[] data = new byte[len];
while((read != len) && (actual != -1)) {
actual = is.read(data, read, len - read);
read += actual;
}

_response = new String(data).toString();
}

is.close();

_params.removeAllElements();
_headers.removeAllElements();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Take a look at this snippet of code…

public void execute(int method) throws Exception { .. }

We define int method by invoking the RestMethod class:

public class RestMethod {
public static final int GET = 0;
public static final int POST = 1;
}

And there you have it. If you have anything else to contribute, please feel free to comment below. Thanks to Tyler Smith, and the other contributors for this evolving code. Happy deving!

UPDATE:

And the NameValuePair class:

public class NameValuePair {
private String _name;
private String _value;

public NameValuePair(String name, String value) {
_name = name;
_value = value;
}

public String getName() {
return _name;
}

public String getValue() {
return _value;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>