Reader small image

You're reading from  Asynchronous Android Programming - Second Edition

Product typeBook
Published inJul 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785883248
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Steve Liles
Steve Liles
author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles

Right arrow

Chapter 8. Interacting with the Network

So far, we have been using the HttpURLConnection HTTP client to transfer data from and to the network, such as when downloading images from an HTTP server and synchronizing information with a remote HTTP server. We have been using this Android HTTP client blindly without going into much detail about the internals and the features provided by this handy framework that deals transparently with the HTTP protocol for us.

In this chapter, we'll learn more about the advanced features of HttpURLConnection and fresh techniques to communicate asynchronously and securely with a remote server using the HTTP protocol.

In the meantime, we will learn how use a customized HTTP client to communicate over secure channels, tweak the HTTP client to deal with network delays, and learn how to interact with web APIs.

In this chapter, we will cover the following:

  • Introducing Android HTTP clients

  • Performing HTTP requests asynchronously

  • Interacting with JSON web APIs

  • Interacting...

Introducing Android HTTP clients


In recent times, the ability to send and receive data from remote servers has become an essential feature that all applications should enforce in order to create dynamic and impressive experiences. Today almost every application uses the network to pull up data information, execute remote business logic operations, and download or upload resources.

The network interactions that happen between the application and a remote server are typically defined as a set of request/response messages that traverse the network using a network protocol.

In general, the HTTP protocol is often used to transport messages between each peer, and the Android SDK comes with two high-level HTTP clients available out of the box to send and receive data: AndroidHttpClient and HttpURLConnection.

The HTTP communication protocol is a stateless, standard text-based application protocol maintained by Internet Engineering Task Force (IETF) and the World Wide Web Consortium (W3C) and is widely...

Performing HTTP requests asynchronously


So far we have been using the HttpURLConnection client and AsyncTask to retrieve remote data asynchronously in our code examples.

While this solution can work in most cases, we could end up with loads of duplicate code in our applications.

In this section, we will create a neat high-level asynchronous HTTP client to perform remote requests outside of the main thread that forwards the result of the request to the application's main thread using a callback handler. This approach fits well with the application UI model because the callback handler, which executes on the main thread, is able to update the UI with the data retrieved from the server.

First of all, let's define the basic interface that our asynchronous client should honor to execute remote requests in the background:

public interface AsyncHTTPClient {
    void execute(HTTPRequest request, ResponseHandler handler);
}

The HTTPRequest class is a Java model used to define all the parameters required...

Customizing HTTP timeouts


When HttpUrlConnection connects, reads, or writes content over a low bandwidth network (2G, 3G, and so on), the exposure to unpredictable communication delays can not be avoided. Moreover, apart from the mobile network delays, the HTTP servers might introduce significant response delays (server latency) when they are experiencing high volumes of traffic.

Although the default timeout values used by the the HttpUrlConnection are long enough to cope with these delays, there are some special use cases where you might want to customize the default values according to your needs. For example, when on the way to the application server, the HTTP request travels through some proxies.

HttpUrlConnection offers us two member methods that can be used to change the default timeouts:

void setConnectTimeout(int timeoutMillis)
void setReadTimeout(int timeoutMillis)

setConnectTimeout(int) is able to redefine the maximum time in milliseconds that our client is allowed to wait until...

Communicating securely over SSL sessions


So far, we have been using plain connections to communicate with a remote HTTP server. Despite the fact that these kinds of connections might fit your application requirements when the data exchanged is not sensitive, there are use cases where we must use a secure channel to send or receive, preventing any third party from reading or changing the data exchanged on the network.

In order to setup an SSL session with a remote server, our client, with the help of some cryptographic tools, will create a cryptographic communication channel where all the data is encrypted with a symmetric cipher that uses a secret key exchanged during the secure connection handshake. Apart from that, the content received and encrypted with a previously exchanged secret key is validated against other peer public keys to prove that the data is coming and signed from the right source.

During the connection establishment, as part of the SSL handshake, the server has to prove that...

Summary


In this chapter, we explored in detail the HttpUrlConnection Android HTTP client and we built a basic and expandable asynchronous client to interact with HTTP web APIs.

In the first section, we exposed the main differences between the HttpUrlConnection client and the deprecated Apache HTTP client available on pre-Marshmallow SDKs.

Next, we wrote the core classes and callback interfaces for our asynchronous client and we expanded our high-level client to interact with JSON and Web APIs. Additionally, we built the code to convert from our Java models to a JSON or an XML document.

Later, we learned how to configure the HTTP timeouts and to set up secure communications that are able to use our own signed certificates, keys, and CAs. In our example, we created and prepared an SSL context to be used to establish a secure channel based on a prepared Java secure keystore.

In the next chapter, we will introduce and explore the JNI (Java Native Interface) to create asynchronous tasks in native...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Asynchronous Android Programming - Second Edition
Published in: Jul 2016Publisher: PacktISBN-13: 9781785883248
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Steve Liles

Steve Liles is a self-confessed geek and has been an Android fan since the launch day of the G1. When he isn't at work building publishing systems and apps for newspapers and magazines, you'll find him tinkering with his own apps, building 3D printers, or playing RTS games. He is currently working with a start-up to build an advertising system that links the print and digital worlds using computer vision on Android and iOS devices.
Read more about Steve Liles