Consuming a REST service from Java (Android)
The time finally came when I need to consume a service from my Android app. As I expected this is not as easy as with JavaScript. Strict types, threads and craziness come all into play for this simple task.
The first thing I learned about making a request to a REST service was to use the apache library:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public String makeRequest(url) {
// HttpRequestBase is the parent of HttpGet, HttpPost, HttpPut
// and HttpDelete
HttpRequestBase request = new HttpGet(url);
// The BasicResponseHandler returns the response as a String
ResponseHandler<String> handler = new BasicResponseHandler();
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
// Pass the handler and request to httpclient
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}