SlideShare a Scribd company logo
Android HTTP Library
Allan Shih
2
Agenda

Introduction

HTTP library
- Apache Http Client
- HttpUrlConnection
- OkHttp
- Volley

Image library
- Picasso
- Glide

Reference
3
Introduction
Most apps use HTTP to send and receive data
4
Introduction
Every thing you need

JSON, images, raw text

Memory and disk caching

Powerful customization
abilities

Simple async interface

Easy to use
5
Available official HTTP Client

Apache HttpClient
- Provides a huge set of APIs/methods
- Full implementation of all HTTP methods
- Support for HTTP/1.1 response caching

HttpURLConnection
- Lightweight HTTP client suitable for most apps
- Transparent compression (Android 2.3)
- Response caching (Android 4.0)
6
Apache HTTP Client
Get server time
7
Apache HTTP Client
Make a default HttpClient
HttpClient client = new DefaultHttpClient();
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
HttpGet httpGet = new HttpGet(params[0]);
httpGet.addHeader("Accept", "application/json");
HttpResponse response = client.execute(httpGet);
return getJsonString(httpResponse);
}
...
}
8
Apache HTTP Client
Add Headers to the request
HttpClient client = new DefaultHttpClient();
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
HttpGet httpGet = new HttpGet(params[0]);
httpGet.addHeader("Accept", "application/json");
HttpResponse response = client.execute(httpGet);
return getJsonString(httpResponse);
}
...
}
9
Apache HTTP Client
Make http request call
HttpClient client = new DefaultHttpClient();
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
HttpGet httpGet = new HttpGet(params[0]);
httpGet.addHeader("Accept", "application/json");
HttpResponse response = client.execute(httpGet);
return getJsonString(httpResponse);
}
...
}
10
HTTPUrlConnection
Getting a connection from a URL
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
URL mURL = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)
mURL.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
result = getJsonString(conn.getInputStream());
conn.disconnect();
}
11
HTTPUrlConnection
Add Headers to the request
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
URL mURL = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)
mURL.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
result = getJsonString(conn.getInputStream());
conn.disconnect();
}
12
HTTPUrlConnection
Read the response
class HttpGetTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
URL mURL = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)
mURL.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
result = getJsonString(conn.getInputStream());
conn.disconnect();
}
13
Problems

Apache HttpClient
- Huge size of library
- Difficult to improve it without breaking compatibility
- Android 6.0 removes support for the Apache HTTP client

HttpURLConnection
- Has some issues on Froyo (Android 2.2)
- Fully-synchronous API
- Not easy to use
OkHttp
An efficient HTTP client developed by Square
15
OkHttp Client

GZIP

HTTP/2

Response caching

Async calls with callbacks

Recover from common connection problems
16
OkHttp Client
Make a default client
private OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(requestURL)
.addHeader("Accept", "application/json")
.build();
Response response =
client.newCall(request).execute();
result = getJsonString(response);
17
OkHttp Client
Synchronous Get
private OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(params[0])
.addHeader("Accept", "application/json")
.build();
Response response = client.newCall(request).execute();
result = getJsonString(response.body().byteStream());
18
OkHttp Client
Asynchronous Get
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
public void onFailure(Request request, Throwable t) {
...
}
public void onResponse(Response response) {
result = getJsonString(response.body().byteStream());
...
}
});
Volley
Easy, Fast Networking for Android
20
What is Volley
A burst or
emission of many
things or a large
amount at once
21
Volley

Automatic scheduling

Response caching

Support prioritization

Cancellation request API

Ease of customization

Debugging and tracing tools
22
Volley architecture
23
Volley
Setting Up a RequestQueue
RequestQueue mRequestQueue =
Volley.newRequestQueue(context);
StringRequest stringRequest =
new StringRequest(Request.Method.GET,
url,
listener,
errorListener);
mRequestQueue.add(getRequest);
24
Volley
Make a GET Request
RequestQueue mRequestQueue =
Volley.newRequestQueue(context);
StringRequest stringRequest =
new StringRequest(Request.Method.GET,
url,
listener,
errorListener);
mRequestQueue.add(getRequest);
25
Volley
Set Response Listener
StringRequest getRequest = new StringRequest(url,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
result = getJsonString(s);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
26
Volley
Set Error Listener
StringRequest getRequest = new StringRequest(url,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
result = getJsonString(s);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
27
Volley
Send POST request with JSON data
...
JsonObjectRequest jsonObjectRequest
= new JsonObjectRequest(Request.Method.POST,
url,
jsonDataObject,
listener,
errorListener);
mRequestQueue.add(jsonObjectRequest);
Benchmark
Using the Google Places Service
29
Google place service
Get current places
30
Google place service
Json data
"results" : [
{
"geometry" : {
"location" : {
"lat" : 25.0352548,
"lng" : 121.5625101
}
},
"id" : "137348ad7b2fc06d1ed646ca215062ccbf",
"name" : "Grand Hyatt Taipei",
"place_id" : "ChIJty1ap7erQjQRWmO-mTv1zkQ",
"rating" : 4,
"scope" : "GOOGLE",
"types" : ["restaurant", "food"],
"vicinity" : "No. 2, Songshou Road, Xinyi District"
},
31
How did I test?
1. 清除 APP 資料
2. 發送 Request 到 Google Place Server
3. 連續送 25 個非同步 Request
4. 使用 Android Studio Monitor 記錄結果
32
Response time (milliseconds)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
0
500
1000
1500
2000
2500
HttpClient HttpUrlConnection OkHttp Volley
Request
ResponseTime(ms)
33
Memory
HttpUrl
Connection
HttpClient OkHttp Volley
108~124.47MB 108~122MB 108~124MB 108~120MB
34
CPU
User mode and Kernel mode
HttpUrl
Connection
HttpClient OkHttp Volley
MAX 30% 38% 27% 33%
35
Network
HttpUrl
Connection
HttpClient OkHttp Volley
MAX 208 KB/s 240 KB/s 260.49 KB/s 24 KB/s
36
HTTP Client Comparison
HttpUrl
Connection
HttpClient OkHttp Volley
Creator Java.net Apache Square inc Google inc
Last version Android 6.0 4.3.5 2.6 1.0.19
Size - 591KB 327KB 91KB
Support HTTP/2 NO NO YES NO
Easy to use NO YES YES YES
Async call NO NO YES YES
Response Cache >= Android 4.0 >= 4.1 YES Enable
Image Loading
Load image from remote URL in ImageView
38
Typical implementation
ImageAsyncTask
public class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... strings) {
HttpURLConnection connection = null;
URL imageUrl = new URL(strings[0]);
connection = (HttpURLConnection) imageUrl.openConnection();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
return BitmapFactory.decodeStream(connection.getInputStream());
}
connection.disconnect();
return null;
}
public void onPostExecute(Bitmap bitmap){
if (bitmap != null) mImageView.setImageBitmap(bitmap);
}
39
Volley
Image Loading

ImgaeRequest
- Specify a URL and receive an image in response
- Image caching is enabled by default

ImageLoader
- A helper class that handles loading and caching images from URLs

NetworkImageView
- Builds on ImageLoader and effectively replaces ImageView
40
Volley
Download image using ImageRequest
...
ImageRequest imageRequest = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
},
width, height,
ImageView.ScaleType.FIT_XY,
Bitmap.Config.RGB_565,
errorListener);
41
Volley
Download image using ImageRequest
...
ImageRequest imageRequest = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
},
width, height,
ImageView.ScaleType.FIT_XY,
Bitmap.Config.RGB_565,
errorListener);
42
Volley
Retrieving images with ImageLoader
ImageLoader imageLoader
= new ImageLoader(mRequestQueue, new BitmapLruCache());
ImageListener listener
= ImageLoader.getImageListener(imageView,
R.drawable.default_image,
R.drawable.failed_image);
imageLoader.get(imageURL, listener, 400, 400);
43
Volley
Download image using NetworkImageView
- <ImageView
+ <com.android.volley.NetworkImageView
XML
mImageView = (NetworkImageView) findViewById(R.id.image);
mImageView.setImageUrl(IMAGE_URL, mImageLoader);
JAVA
44
Picasso and Glide

Picasso
- Complex image transformations
- Automatic memory and disk caching
- ImageView recycling and download cancelation

Glide
- Fast loading big images from internet
- GIF (animated image) support
- Recommended by Google
45
Load image from url to ImageView
Picasso.with(context).load(url).into(view);
Picasso
Glide.with(context).load(url).into(view);
Glide
46
Re-size the image
Picasso.with(context).load(url)
.resize(200, 200).into(view);
Picasso
Glide.with(context).load(url)
.override(200, 200).into(view);
Glide
47
GIF (animated image) support
48
Image Loading
1920x1080 image is loaded into 768x432 ImageView
49
Image Loader Comparison
Volley Picasso Glide
Creator Google inc Square inc BumpTech
Last version 1.0.19 2.5.2 3.6.1
Size 91KB 120KB 464KB
Speed
GIF support NO NO YES
Easy to use
Image Caching YES YES YES
50
Relationships between the libraries
51
Reference
1. HttpUrlConnection
2. Apache HTTP Client https://hc.apache.org/httpcomponents-client-ga/
3. Square OkHttp http://square.github.io/okhttp/
4. Volley documentation https://developer.android.com/training/volley
5. Picasso http://square.github.io/picasso/
6. Glide https://github.com/bumptech/glide
7. Which Android HTTP library to use?
8. HTTP 2.0

More Related Content

What's hot

Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)
Adnan Sohail
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Svetlin Nakov
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Json
JsonJson
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithm
Alexey Fyodorov
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Http protocol
Http protocolHttp protocol
Http protocol
Arpita Naik
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JSON Web Tokens
JSON Web TokensJSON Web Tokens
JSON Web Tokens
Ivan Rosolen
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
Lena Petsenchuk
 
Xslt
XsltXslt
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
Mallikarjuna G D
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
Sahil Agarwal
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
VMware Tanzu
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 

What's hot (20)

Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Java Script Object Notation (JSON)
Java Script Object Notation (JSON)Java Script Object Notation (JSON)
Java Script Object Notation (JSON)
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Json
JsonJson
Json
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
 
Non-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithmNon-blocking Michael-Scott queue algorithm
Non-blocking Michael-Scott queue algorithm
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Http protocol
Http protocolHttp protocol
Http protocol
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JSON Web Tokens
JSON Web TokensJSON Web Tokens
JSON Web Tokens
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
Xslt
XsltXslt
Xslt
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 

Similar to Android httpclient

Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
Alexei Skachykhin
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
Randy Connolly
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
caohansnnuedu
 
Rpi python web
Rpi python webRpi python web
Rpi python web
sewoo lee
 
Performance #4 network
Performance #4  networkPerformance #4  network
Performance #4 network
Vitali Pekelis
 
Volley - Android Networking
Volley - Android NetworkingVolley - Android Networking
Volley - Android Networking
Tai Dang
 
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIsHTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
Roan Brasil Monteiro
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
Adrian Cole
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
Synapseindiappsdevelopment
 
Android Performance #4: Network
Android Performance #4: NetworkAndroid Performance #4: Network
Android Performance #4: Network
Yonatan Levin
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
ASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep DiveASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep Dive
Jon Galloway
 
Http2 kotlin
Http2   kotlinHttp2   kotlin
Http2 kotlin
Andrii Bezruchko
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
Aravindharamanan S
 
OpenStack APIs: Present and Future (Beta Talk)
OpenStack APIs: Present and Future (Beta Talk)OpenStack APIs: Present and Future (Beta Talk)
OpenStack APIs: Present and Future (Beta Talk)
Wade Minter
 
Android http library
Android http libraryAndroid http library
Android http library
Francesco Azzola
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009
sullis
 
Middleware in Asp.Net Core
Middleware in Asp.Net CoreMiddleware in Asp.Net Core
Middleware in Asp.Net Core
Shahriar Hossain
 

Similar to Android httpclient (20)

Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
Rpi python web
Rpi python webRpi python web
Rpi python web
 
Performance #4 network
Performance #4  networkPerformance #4  network
Performance #4 network
 
Volley - Android Networking
Volley - Android NetworkingVolley - Android Networking
Volley - Android Networking
 
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIsHTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
HTTP / 1, HTTP / 2 and HTTP / 3: Past, present and the future of APIs
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
Android Performance #4: Network
Android Performance #4: NetworkAndroid Performance #4: Network
Android Performance #4: Network
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)
 
ASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep DiveASP.NET Core 3.0 Deep Dive
ASP.NET Core 3.0 Deep Dive
 
Http2 kotlin
Http2   kotlinHttp2   kotlin
Http2 kotlin
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
OpenStack APIs: Present and Future (Beta Talk)
OpenStack APIs: Present and Future (Beta Talk)OpenStack APIs: Present and Future (Beta Talk)
OpenStack APIs: Present and Future (Beta Talk)
 
Android http library
Android http libraryAndroid http library
Android http library
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009
 
11 asp.net web api
11 asp.net web api11 asp.net web api
11 asp.net web api
 
Middleware in Asp.Net Core
Middleware in Asp.Net CoreMiddleware in Asp.Net Core
Middleware in Asp.Net Core
 

More from allanh0526

Webp
WebpWebp
Digital authentication
Digital authenticationDigital authentication
Digital authentication
allanh0526
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkins
allanh0526
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slather
allanh0526
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
allanh0526
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcode
allanh0526
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
allanh0526
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
allanh0526
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
allanh0526
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swift
allanh0526
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swift
allanh0526
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
allanh0526
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
allanh0526
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
allanh0526
 
WebRTC
WebRTCWebRTC
WebRTC
allanh0526
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interface
allanh0526
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archiva
allanh0526
 

More from allanh0526 (18)

Webp
WebpWebp
Webp
 
Digital authentication
Digital authenticationDigital authentication
Digital authentication
 
Integration of slather and jenkins
Integration of slather and jenkinsIntegration of slather and jenkins
Integration of slather and jenkins
 
How to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slatherHow to generate code coverage reports in xcode with slather
How to generate code coverage reports in xcode with slather
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
Ui testing in xcode
Ui testing in xcodeUi testing in xcode
Ui testing in xcode
 
How to work with dates and times in swift 3
How to work with dates and times in swift 3How to work with dates and times in swift 3
How to work with dates and times in swift 3
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
ThingMaker in Swift
ThingMaker in SwiftThingMaker in Swift
ThingMaker in Swift
 
Automatic reference counting in Swift
Automatic reference counting in SwiftAutomatic reference counting in Swift
Automatic reference counting in Swift
 
Core data in Swfit
Core data in SwfitCore data in Swfit
Core data in Swfit
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
 
WebRTC
WebRTCWebRTC
WebRTC
 
Pipeline interface
Pipeline interfacePipeline interface
Pipeline interface
 
Deploying artifacts to archiva
Deploying artifacts to archivaDeploying artifacts to archiva
Deploying artifacts to archiva
 

Recently uploaded

First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 

Recently uploaded (20)

First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 

Android httpclient

  • 2. 2 Agenda  Introduction  HTTP library - Apache Http Client - HttpUrlConnection - OkHttp - Volley  Image library - Picasso - Glide  Reference
  • 3. 3 Introduction Most apps use HTTP to send and receive data
  • 4. 4 Introduction Every thing you need  JSON, images, raw text  Memory and disk caching  Powerful customization abilities  Simple async interface  Easy to use
  • 5. 5 Available official HTTP Client  Apache HttpClient - Provides a huge set of APIs/methods - Full implementation of all HTTP methods - Support for HTTP/1.1 response caching  HttpURLConnection - Lightweight HTTP client suitable for most apps - Transparent compression (Android 2.3) - Response caching (Android 4.0)
  • 7. 7 Apache HTTP Client Make a default HttpClient HttpClient client = new DefaultHttpClient(); class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { HttpGet httpGet = new HttpGet(params[0]); httpGet.addHeader("Accept", "application/json"); HttpResponse response = client.execute(httpGet); return getJsonString(httpResponse); } ... }
  • 8. 8 Apache HTTP Client Add Headers to the request HttpClient client = new DefaultHttpClient(); class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { HttpGet httpGet = new HttpGet(params[0]); httpGet.addHeader("Accept", "application/json"); HttpResponse response = client.execute(httpGet); return getJsonString(httpResponse); } ... }
  • 9. 9 Apache HTTP Client Make http request call HttpClient client = new DefaultHttpClient(); class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { HttpGet httpGet = new HttpGet(params[0]); httpGet.addHeader("Accept", "application/json"); HttpResponse response = client.execute(httpGet); return getJsonString(httpResponse); } ... }
  • 10. 10 HTTPUrlConnection Getting a connection from a URL class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { URL mURL = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); result = getJsonString(conn.getInputStream()); conn.disconnect(); }
  • 11. 11 HTTPUrlConnection Add Headers to the request class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { URL mURL = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); result = getJsonString(conn.getInputStream()); conn.disconnect(); }
  • 12. 12 HTTPUrlConnection Read the response class HttpGetTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... params) { URL mURL = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); result = getJsonString(conn.getInputStream()); conn.disconnect(); }
  • 13. 13 Problems  Apache HttpClient - Huge size of library - Difficult to improve it without breaking compatibility - Android 6.0 removes support for the Apache HTTP client  HttpURLConnection - Has some issues on Froyo (Android 2.2) - Fully-synchronous API - Not easy to use
  • 14. OkHttp An efficient HTTP client developed by Square
  • 15. 15 OkHttp Client  GZIP  HTTP/2  Response caching  Async calls with callbacks  Recover from common connection problems
  • 16. 16 OkHttp Client Make a default client private OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(requestURL) .addHeader("Accept", "application/json") .build(); Response response = client.newCall(request).execute(); result = getJsonString(response);
  • 17. 17 OkHttp Client Synchronous Get private OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(params[0]) .addHeader("Accept", "application/json") .build(); Response response = client.newCall(request).execute(); result = getJsonString(response.body().byteStream());
  • 18. 18 OkHttp Client Asynchronous Get Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { public void onFailure(Request request, Throwable t) { ... } public void onResponse(Response response) { result = getJsonString(response.body().byteStream()); ... } });
  • 20. 20 What is Volley A burst or emission of many things or a large amount at once
  • 21. 21 Volley  Automatic scheduling  Response caching  Support prioritization  Cancellation request API  Ease of customization  Debugging and tracing tools
  • 23. 23 Volley Setting Up a RequestQueue RequestQueue mRequestQueue = Volley.newRequestQueue(context); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, listener, errorListener); mRequestQueue.add(getRequest);
  • 24. 24 Volley Make a GET Request RequestQueue mRequestQueue = Volley.newRequestQueue(context); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, listener, errorListener); mRequestQueue.add(getRequest);
  • 25. 25 Volley Set Response Listener StringRequest getRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { result = getJsonString(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } });
  • 26. 26 Volley Set Error Listener StringRequest getRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { result = getJsonString(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } });
  • 27. 27 Volley Send POST request with JSON data ... JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonDataObject, listener, errorListener); mRequestQueue.add(jsonObjectRequest);
  • 28. Benchmark Using the Google Places Service
  • 29. 29 Google place service Get current places
  • 30. 30 Google place service Json data "results" : [ { "geometry" : { "location" : { "lat" : 25.0352548, "lng" : 121.5625101 } }, "id" : "137348ad7b2fc06d1ed646ca215062ccbf", "name" : "Grand Hyatt Taipei", "place_id" : "ChIJty1ap7erQjQRWmO-mTv1zkQ", "rating" : 4, "scope" : "GOOGLE", "types" : ["restaurant", "food"], "vicinity" : "No. 2, Songshou Road, Xinyi District" },
  • 31. 31 How did I test? 1. 清除 APP 資料 2. 發送 Request 到 Google Place Server 3. 連續送 25 個非同步 Request 4. 使用 Android Studio Monitor 記錄結果
  • 32. 32 Response time (milliseconds) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 0 500 1000 1500 2000 2500 HttpClient HttpUrlConnection OkHttp Volley Request ResponseTime(ms)
  • 34. 34 CPU User mode and Kernel mode HttpUrl Connection HttpClient OkHttp Volley MAX 30% 38% 27% 33%
  • 35. 35 Network HttpUrl Connection HttpClient OkHttp Volley MAX 208 KB/s 240 KB/s 260.49 KB/s 24 KB/s
  • 36. 36 HTTP Client Comparison HttpUrl Connection HttpClient OkHttp Volley Creator Java.net Apache Square inc Google inc Last version Android 6.0 4.3.5 2.6 1.0.19 Size - 591KB 327KB 91KB Support HTTP/2 NO NO YES NO Easy to use NO YES YES YES Async call NO NO YES YES Response Cache >= Android 4.0 >= 4.1 YES Enable
  • 37. Image Loading Load image from remote URL in ImageView
  • 38. 38 Typical implementation ImageAsyncTask public class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... strings) { HttpURLConnection connection = null; URL imageUrl = new URL(strings[0]); connection = (HttpURLConnection) imageUrl.openConnection(); if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){ return BitmapFactory.decodeStream(connection.getInputStream()); } connection.disconnect(); return null; } public void onPostExecute(Bitmap bitmap){ if (bitmap != null) mImageView.setImageBitmap(bitmap); }
  • 39. 39 Volley Image Loading  ImgaeRequest - Specify a URL and receive an image in response - Image caching is enabled by default  ImageLoader - A helper class that handles loading and caching images from URLs  NetworkImageView - Builds on ImageLoader and effectively replaces ImageView
  • 40. 40 Volley Download image using ImageRequest ... ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap bitmap) { imageView.setImageBitmap(bitmap); } }, width, height, ImageView.ScaleType.FIT_XY, Bitmap.Config.RGB_565, errorListener);
  • 41. 41 Volley Download image using ImageRequest ... ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap bitmap) { imageView.setImageBitmap(bitmap); } }, width, height, ImageView.ScaleType.FIT_XY, Bitmap.Config.RGB_565, errorListener);
  • 42. 42 Volley Retrieving images with ImageLoader ImageLoader imageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache()); ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.default_image, R.drawable.failed_image); imageLoader.get(imageURL, listener, 400, 400);
  • 43. 43 Volley Download image using NetworkImageView - <ImageView + <com.android.volley.NetworkImageView XML mImageView = (NetworkImageView) findViewById(R.id.image); mImageView.setImageUrl(IMAGE_URL, mImageLoader); JAVA
  • 44. 44 Picasso and Glide  Picasso - Complex image transformations - Automatic memory and disk caching - ImageView recycling and download cancelation  Glide - Fast loading big images from internet - GIF (animated image) support - Recommended by Google
  • 45. 45 Load image from url to ImageView Picasso.with(context).load(url).into(view); Picasso Glide.with(context).load(url).into(view); Glide
  • 46. 46 Re-size the image Picasso.with(context).load(url) .resize(200, 200).into(view); Picasso Glide.with(context).load(url) .override(200, 200).into(view); Glide
  • 48. 48 Image Loading 1920x1080 image is loaded into 768x432 ImageView
  • 49. 49 Image Loader Comparison Volley Picasso Glide Creator Google inc Square inc BumpTech Last version 1.0.19 2.5.2 3.6.1 Size 91KB 120KB 464KB Speed GIF support NO NO YES Easy to use Image Caching YES YES YES
  • 51. 51 Reference 1. HttpUrlConnection 2. Apache HTTP Client https://hc.apache.org/httpcomponents-client-ga/ 3. Square OkHttp http://square.github.io/okhttp/ 4. Volley documentation https://developer.android.com/training/volley 5. Picasso http://square.github.io/picasso/ 6. Glide https://github.com/bumptech/glide 7. Which Android HTTP library to use? 8. HTTP 2.0