Let's Talk:
Efficient Communication
between PHP and Android
Matthew Turland
I Work Here
- Internet solutions for ISPs, media companies, and advertisers
- Offices in Buffalo, New York City, and Atlanta
- Clientele includes most of the top 20 USA cable providers
- Great company to work for - join us!
Lay of the Land
- Mobile: where it's at
- Service-oriented architecture: ahead of its time
- Increased mobile device availability = increased network strain
- Pinch bandwidth like we did memory in the Old Days (tm)
Objectives
- Build a PHP-based REST web service
- Build an Android (2.3+) client to consume that service
- Explore approaches to efficient communication between the two
- data serialization
- data compression
Presumptions
- You have a basic working knowledge of PHP
- You have a basic working knowledge of Android
HTTP
- RFC 2616 defines the Hypertext Transfer Protocol or HTTP
- Some related references:
REST
A Common Request
GET /foo HTTP/1.1
Accept: application/json;q=1, application/xml;q=0.5
Accept-Encoding: gzip, deflate
A Common Response
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: gzip
...
Client Needs Internet Access
Client Needs an HTTP Client
- Facilitates communication with REST services
- HttpURLConnection is available in all Android versions
Keeping It Asynchronous
- If you block the main (UI) thread, you're going to have a bad time
- Wrap your request logic in an AsyncTask (example) or a service
Accessing Local Services
- If the machine hosting your service is accessible to your Android application by...
- ... your app running in an emulator on that machine, access the service on IP 10.0.2.2
- ... your app running on a device plugged into that machine via USB, access the service on IP 10.0.1.2
- Otherwise, your Android application can generally access any machine the host can access using the same hostname
Server Supported Types
Client Supported Types
Deriving Best Type
Content Negotiation
- What we just did to figure out what type to return
- Detailed in RFC 2616 Section 12
- Also works for encoding, character set, and language
Content Compression
Server Compression Schemes
Client Compression Schemes
Deriving Best
Compression Scheme
By the Numbers
- PHP 5.4.12 with Xdebug 2.2.1 for profiling
- Intel C2D 1.83GHz, 4 GB RAM
- YMMV — experiment with types and compression schemes
- TL;DR: if you can, use bzip2
Scheme |
Size (b) |
Size (ratio) |
Runtime (ms) |
None |
10,337 |
1.000 |
0.000 |
bzip2 |
1,515 |
0.147 |
7.010 |
gzip |
1,712 |
0.166 |
0.996 |
deflate |
1,716 |
0.166 |
0.858 |
Back to the Client
Decoding the Response
Batteries Not Included
Stream to String
Parsing the Response
Response Caching
- Related headers detailed in subsections of RFC 2616 Section 14
- Server returns a 304 status if the response has not changed
- Two methods
- If your minimum Android version is Ice Cream Sandwich or higher (>= 4.0/API level 14), use HttpResponseCache