Site Loader

Introduction

REST is Representational state
transfer technology. It is a simple
way of sending and receiving data between client and server. One can send and
receive data as JSON, XML or even plain text. It’s light weighted compared to
SOAP. Android SDK contains classes and methods which are used to
connect to remote web servers. These methods can also interact with web servers
using REST APIs. In this document we will see how to use REST API to connect
and interact with web server in Android.

We Will Write a Custom Essay Specifically
For You For Only $13.90/page!


order now

 Accessing Internet

To use REST API, we need internet. We need android.permission.INTERNET permission
to access the internet. So
we should ask permission from user. To ask, we need to add following uses-permission tag:

 

Background Threads

We cannot run network code on the main thread of the
application. Networking code must be present in background thread. To create a
new thread, use the execute() method
of the AsyncTask class

AsyncTask.execute(new
Runnable() {

    @Override

    public
void run() {

        //
All networking code should be here

        

    }

});

HTTP Connection

To set up a connection to REST endpoint we use openConnection() method of URL
class. openConnection() returns a
value. This value should be cast to an instance of HttpURLConnection
or HttpsURLConnection , based on object
is HTTPS or HTTP. Both HttpsURLConnection and HttpURLConnection has methods to
perform operations such as reading responses and adding request headers.

Below code shows how to set up a connection with the Google’s
API’s root endpoint:

//
Create URL

URL
googleEndpoint = new URL(“https:// api.google.com
/”);

 

//
Create connection

HttpsURLConnection
myconnection =

        (HttpsURLConnection)
googleEndpoint.openConnection();

Adding Request Headers

Most websites which gives REST APIs wants to track/identify our
app uniquely. They include a unique header called User-Agent in all their requests. to We must
use the setRequestProperty() method of
the HttpURLConnection object to add
a User-Agent header.

myConnection.setRequestProperty(“User-Agent”,
“my-rest-app-v1.1”);

By calling the setRequestProperty() method
many times we can add many headers to the request. For example, the following
code adds an About-US header and a custom Contact header:

myConnection.setRequestProperty(“About-US”,

        “application/vnd.google.v3+json”);

myConnection.setRequestProperty(“Contact”,

        “[email protected]”);

Reading Responses

To check valid response after passing all request headers we use
function named getResponseCode().It is method of HttpURLConnection object.

if
(myConnection.getResponseCode() == 100) {

    //
Success in getting response

    }
else {

    //
Error code goes here

}

If response code 301 is received from the HttpURLConnection class, HttpURLConnection class handles
it automatically and follows the redirect. So no extra code should be written
to check for redirects response.

To get a reference to the input stream of the connection a
method should be called which is
getInputStream() 

InputStream
response = myConnection.getInputStream();

Many REST APIs return data as JSON documents. Instead of reading
from the InputStream object directly, InputStreamReader should be created.

InputStreamReader
responseReader =

        new
InputStreamReader(response, “UTF-8”);

Parsing JSON Responses

There is class called JsonReader which is present in Android
SDK. It helps to parse JSON data. An object of JsonReader class can be created
by passing the InputStreamReader object to its constructor.

JsonReader
jsonreader = new JsonReader(responseReader);

Suppose the JSON document returned by the root endpoint of
Facebook’s REST has following parameters:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

{
  “current_user_url”:
“https://api.facebook.com/user”,
  “current_user_authorizations_html_url”:
“https://facebook.com/settings/connections/applications{/client_id}”,
  “authorizations_url”:
“https://api.facebook.com/authorizations”,
  “code_search_url”:
“https://api.facebook.com/search/code?q={query}{&page,per_page,sort,order}”,
  “emails_url”:
“https://api.facebook.com/user/emails”,
  “emojis_url”:
“https://api.facebook.com/emojis”,
  “events_url”:
“https://api.facebook.com/events”,
  “feeds_url”:
“https://api.facebook.com/feeds”,
  “followers_url”:
“https://api.facebook.com/user/followers”,
  “following_url”:
“https://api.facebook.com/user/following{/target}”,
  “gists_url”:
“https://api.facebook.com/gists{/gist_id}”,
  “hub_url”:
“https://api.facebook.com/hub”,
  “issue_search_url”:
“https://api.facebook.com/search/issues?q={query}{&page,per_page,sort,order}”,
  “issues_url”:
“https://api.facebook.com/issues”,
  “keys_url”:
“https://api.facebook.com/user/keys”,
  “notifications_url”:
“https://api.facebook.com/notifications”,
  “organization_repositories_url”:
“https://api.facebook.com/orgs/{org}/repos{?type,page,per_page,sort}”,
  “organization_url”:
“https://api.facebook.com/orgs/{org}”,
  “public_gists_url”:
“https://api.facebook.com/gists/public”,
  “rate_limit_url”:
“https://api.facebook.com/rate_limit”,
  “repository_url”:
“https://api.facebook.com/repos/{owner}/{repo}”,
  “repository_search_url”:
“https://api.facebook.com/search/repositories?q={query}{&page,per_page,sort,order}”,
  “current_user_repositories_url”:
“https://api.facebook.com/user/repos{?type,page,per_page,sort}”,
  “starred_url”:
“https://api.facebook.com/user/starred{/owner}{/repo}”,
  “starred_gists_url”:
“https://api.facebook.com/gists/starred”,
  “team_url”:
“https://api.facebook.com/teams”,
  “user_url”:
“https://api.facebook.com/users/{user}”,
  “user_organizations_url”:
“https://api.facebook.com/user/orgs”,
  “user_repositories_url”:
“https://api.facebook.com/users/{user}/repos{?type,page,per_page,sort}”,
  “user_search_url”:
“https://api.facebook.com/search/users?q={query}{&page,per_page,sort,order}”
}

The response a JSON object that contains many keys. For
extracting value of the key called emojis _url from
it, you will have to write the following code:

jsonreader.beginObject();
// Start executing the JSON object

while
(jsonReader.hasNext()) { // Looping all keys

    String
key = jsonreader.nextName(); // Fetch the next key

    if
(key.equals(“emojis_url”)) { // Check if desired key

        //
Fetch the value as a String

        String
value = jsonreader.nextString();

         

        break;
// Break out of the loop

    }
else {

        jsonreader.skipValue();
// Skip values of other keys

    }

}

This code processes the JSON response as a series of tokens.
That’s why it takes very less memory. It can be slow while handling large
responses as it has to process every single token one after another.

After extracting all the required information, the close() method of the JsonReader object should be
called to release all the resources it has.

jsonreader.close();

disconnect() method of the HttpURLConnection object should
be called to disconnect the connection.

myconnection.disconnect();

Different HTTP Methods

To determine the type of operation that has to be performed on a
resource HTTP methods are used by HTTP-based REST interfaces. In the previous
steps, HTTP GET method was used to perform a
read operation. GET method is used by HttpURLConnection class by
default, no need to specify it explicitly. setRequestMethod()method
should be used to change the HTTP method of HttpURLConnection object.

Following code opens a connection to an endpoint that belongs
to  android.org and
its HTTP method is set to POST:

1
2
3
4
5

URL
httppoint = new URL(” https://android.org/post”);
HttpsURLConnection
myConnection
        =
(HttpsURLConnection) httppoint.openConnection();
 
myConnection.setRequestMethod(“POST”);

POST requests are used
to send data to the server. Call setDoOutput() method
of the HttpURLConnection object and
pass True to it. Any data can
be added to the body of the POST request
by writing to the output stream of the connection. The following code shows is
used send a key-value pair to the server:

1
2
3
4
5
6
7
8

//
Create the data
String
data = “message=Infosys”;
 
//
Enable writing
myConnection.setDoOutput(true);
 
//
Write the data
myConnection.getOutputStream().write(myData.getBytes());

Caching responses

To reduce app’s bandwidth consumption and make it more
responsive cache HTTP responses Android SDK has a class called HttpResponseCache. It implements caching
without making any changes to existing networking code.Call the install() method of the HttpResponseCache class to
install a cache for application. The method needs an absolute path as an
parameter specifying where the cache must be installed and other parameter:
number specifying the size of the cache. getCacheDir() method  can be used if specific path is not needed.
The following code installs a cache whose size is 300,000 bytes:

1
2

HttpResponseCache
mcCache = HttpResponseCache.install(
                                getCacheDir(),
300000L);

 

The HttpURLConnection class
starts using cache once the it is installed. To check if cache is working, getHitCount() method is used. It
returns the number of HTTP responses that were served from the cache.

1
2
3

if
(myCache.getHitCount() > 0) {
    //
The cache worked
}

 

Post Author: admin

x

Hi!
I'm Stuart!

Would you like to get a custom essay? How about receiving a customized one?

Check it out