Week8.pptx

COIT20270 Application Development for Mobile Platforms Week 8: Networking

Dr. R. Balsys, CQU, 2018.

Source: Beginning Android Programming with Android Studio, J.F. DiMarzio, 2016

Week 8 – Networking

This week we:

Connect to the web using HTTP

Use XML web services

Use Jason web services

2

CQU - COIT20270 Application Development for Mobile Platforms

Using the HTTP web services

HTTP is used as the main protocol in the WWW

It is used in tasks such as downloading web pages, and binary data such as images, sound and video

To use the HTTP protocol your app must set the uses INTERNET permission in your Android manifest file

You use the OpenHttpConnection() method that takes an URL string as parameter to open a connection to the specified URL

By opening an InputStream object you can download bytes from the URL

3

CQU - COIT20270 Application Development for Mobile Platforms

…Using the HTTP web services

You must set the connection method using setRequestMethod(). Usually you use the HTTP GET verb for this

When the connection is established a HTTP response code is returned. If this is HTTP_OK then you can proceed to get the data using getInputStream()

4

CQU - COIT20270 Application Development for Mobile Platforms

Downloading Binary Data

To download an image from a web server you use the synchronous DownloadImage() method. This returns a Bitmap object. It does this by opening a HTTP connection to the URL and uses the decodeStream() method of the BitmapFactory class to decode the InputStream instance and return it as a Bitmap

Since Android 3.0 all synchronous tasks must be wrapped in the AsyncTask class to prevent them from stalling the UI

You create a DownloadImageTask that extends AsyncTask<String, Void, Bitmap>

5

CQU - COIT20270 Application Development for Mobile Platforms

…Downloading Binary Data

In the DownloadImageTask class you define the methods doInBackground() and onPostExecute()

In doInBackground() you call DownloadImage() to get the bitmap

In onPostExecute() you display the image in your UI using a UI element

You call your DownloadImageTask class by creating an instance of it in onCreate() and then calling execute() on the instance, passing a URL as the parameter

6

CQU - COIT20270 Application Development for Mobile Platforms

…Downloading Binary Data

To read multiple images you modify the doInBackground() method to use a for loop to loop through each of the URLs. As each image is completed you call publishProgress() to give feedback

An extra onProgressUpdate() method is defined in the DownloadImageTask class to display the downloaded images

In onCreate() you pass multiple URLs as the parameters of the execute() method

NOTE: On the emulator localhost refers to the emulator itself. If getting images from your PC use your PCs IP address instead of localhost or the files will not be found

7

CQU - COIT20270 Application Development for Mobile Platforms

Downloading Text

In some circumstances you may wish to GET plain text files. The text file is stored as a String on the device

To achieve this write a DownLoadText(URL) method that returns the text file as a single String

You open a Http connection to an InputStream object. Then use an InputStreamReader instance to a new InputStreamReader() instantiated with your InputStream object

You read the incoming stream of bytes into character buffers and append the incoming String copy of the buffer contents to the final returned String

You create a subclass of AsyncTask to call DownLoadText(URL) asynchronously as before

8

CQU - COIT20270 Application Development for Mobile Platforms

Accessing Web Services using GET

Many Web services respond to a GET query with an XML file

We need to be able to connect to the web service and then parse the contents of the XML file

For example consider a web service that returns the dictionary definition of the word (eg http://services.aonware.com/DictService / DictService.asmx?op=word )

Here you need to establish the connection to the web service and then parse the XML returned

9

CQU - COIT20270 Application Development for Mobile Platforms

…Accessing Web Services using GET

Here we create a WordDefinition(String) method that returns the XML file in a local String object. We wrap this in a subclass of AsyncTask and call WordDefinition (String) asynchronously

Use OpenHttpConnection() and pass the request string as the URL, remembering to use the required word at the end of the string

You create a local instance of a Document object and use the newInstance() method of the DocumentBuilderFactory class to create a DocumentBuilderFactory instance

10

CQU - COIT20270 Application Development for Mobile Platforms

…Accessing Web Services using GET

You also need a DocumentBuilder object defined and then you can use your DocumentBuilderFactory instance to try and get a valid DocumentBuilder object. You call the parse() method get a Document object

The elements of the word definition are then found within the <definition> tags in the Document object model (DOM)

11

CQU - COIT20270 Application Development for Mobile Platforms

Consuming Jason Services

XML has a number of disadvantages:

Documents sizes get big as the complexity goes up and so costs rise

Parsing the XML to extract the content of the message is CPU intensive, requires the complete DOM to be stored locally as a tree structure so is memory intensive

A more efficient representation scheme is to use JavaScript object notation (JSON) to encode the information

12

CQU - COIT20270 Application Development for Mobile Platforms

JASON

JavaScript Object Notation (JSON) is a data exchange format for defining data structures

JSON is light-weight and easy to read and write

JASON objects are represented as “key”:”value” pairs enclosed in {}’s, eg. {"a":"I", "b": ["d", "e", "f"], "c":{"a": 1000, "b":["fred"]} }

13

CQU - COIT20270 Application Development for Mobile Platforms

Consuming JSON Services

To consume JSON services you create a readJSONFeed() method

This method connects to the specified URL and then reads the response from the web service as a String

You call the readJSONFeed() method asynchronously using the AsyncTask class

readJSONFeed() in called in the AsyncTask’s doInBackground() method and the JSON String you fetch is passed into the onPostExecute() method of the AsyncTask

14

CQU - COIT20270 Application Development for Mobile Platforms

Go to the API and read through the entries

14

…Consuming JSON Services

To obtain the list of objects in the JSON String you pass the JSON received into a JSONArray() constructor to get a local JSONArray object representing the JSON data

You can then use the length() method to get the length of the JSON array and get a JSONObject from the JSONArray using the getJSONObject() method

To get the key:value pair from a JSON object you use getString(), getInt(), getLong() or get Boolean()

15

CQU - COIT20270 Application Development for Mobile Platforms

Go to the API and read through the entries

15