Slide 1

Slide 1 text

3as Networking Fundamentals #5 28/11/2017 Britt Barak

Slide 2

Slide 2 text

First,

Slide 3

Slide 3 text

Largest Android Community Android Academy - TLV TLV - Android Academy ~ 2000 members Join Us:

Slide 4

Slide 4 text

Britt Barak @brittBarak ● Google developer expert ● Android Academy ● Women Techmakers

Slide 5

Slide 5 text

Android Academy Staff Yonatan Levin Google Developer Expert & CTO @ KolGene Britt Barak Google Developer Expert Yossi Segev Mobile engineer Colu

Slide 6

Slide 6 text

Mentors program

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

How to perform a network request?

Slide 11

Slide 11 text

How to perform a network request? 1. Ask permission

Slide 12

Slide 12 text

Pleeeeeeaaaase…..?

Slide 13

Slide 13 text

Apps must explicitly request access to resources and data outside their sandbox.

Slide 14

Slide 14 text

AndroidManifest.xml

Slide 15

Slide 15 text

Normal Granted by OS Permission Types Click for documentation Dangerous Granted by user Click for documentation

Slide 16

Slide 16 text

API 22- : Upon Install

Slide 17

Slide 17 text

developer.android.com/training/permissions/requesting.html API 23+ : Runtime

Slide 18

Slide 18 text

developer.android.com/training/permissions/requesting.html API 23+ : Runtime

Slide 19

Slide 19 text

Questions?

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

Client Server Request Response

Slide 22

Slide 22 text

● Hypertext Transfer Protocol. ● Stateless protocol. ● By default: HTTP uses port 80 and HTTPS uses port 443 HTTP

Slide 23

Slide 23 text

Request Verb + URL (+ Payload)

Slide 24

Slide 24 text

HTTP Verb ● GET: fetch an existing resource, by the URL’s info. ● POST: create a new resource, by the request’s payload. ● PUT: update an existing resource, by the request’s payload. ● DELETE: delete an existing resource.

Slide 25

Slide 25 text

URL (Universal Resource Locator) http://www.domain.com:1234/ path/to/resource ?language=english&place=tlv protocol host port path Query parameters

Slide 26

Slide 26 text

Response Status Code + Payload (body)

Slide 27

Slide 27 text

Status Code 1xx: Informational Messages - Expect: 100-continue 2xx: Successful - 200 OK, 204 No Content 3xx: Redirection - Additional action needed. Commonly go to another url. 4xx: Client Error - 404 Not Found, 400 Bad Request,401 Unauthorized, 5xx: Server Error - 503 Service Unavailable

Slide 28

Slide 28 text

Overlook

Slide 29

Slide 29 text

URL url = new URL(myurl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); // Starts the query urlConnection.connect(); int response = urlConnection.getResponseCode(); is = urlConnection.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString;

Slide 30

Slide 30 text

UI Thread #1 Rule Never block it

Slide 31

Slide 31 text

NetworkOnMainThreadException

Slide 32

Slide 32 text

OMG!

Slide 33

Slide 33 text

Luckily, we have

Slide 34

Slide 34 text

Luckily, we have square.github.io

Slide 35

Slide 35 text

Retrofit http://square.github.io/retrofit/ https://futurestud.io/blog/retrofit-getting-started-and-android-client

Slide 36

Slide 36 text

build.gradle() dependencies { //... implementation 'com.squareup.retrofit2:retrofit:2.3.0' }

Slide 37

Slide 37 text

Server Json Android App Java Retrofit

Slide 38

Slide 38 text

Request Verb + URL (+ Payload)

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

https://api.foursquare.com/v2/ venues/explore Base url / Host Path / Endpoint ll Query

Slide 42

Slide 42 text

static final String BASE_URL = "https://api.foursquare.com/v2/"; ServiceGenerator.java

Slide 43

Slide 43 text

@GET("venues/explore") Call getVenues(); public interface FoursquareService ?

Slide 44

Slide 44 text

@GET("venues/explore") Call getVenues(@Query("ll") String location); public interface FoursquareService

Slide 45

Slide 45 text

@GET("venues/explore") Call getVenues( @QueryMap Map options); @GET("venues/{VENUE_ID}/photos") Call getPhotos( @Path("VENUE_ID") String venueId); //an example I made up :) @POST("venues/add") Call addVenue( @Header("Authorization") String authorization, @Body("name") Venue venue);

Slide 46

Slide 46 text

Questions?

Slide 47

Slide 47 text

Response Status Code + Payload (body)

Slide 48

Slide 48 text

What language does the server speak?

Slide 49

Slide 49 text

"groups": [ { "type": "Recommended Places", "name": "recommended", "items": [ { "reasons": { "count": 0, "items": [ { "summary": "This spot is popular", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": {

Slide 50

Slide 50 text

● Advanced REST Client ● Postman ● Swagger ● ….

Slide 51

Slide 51 text

Server Json Android App Java Serialization De-Serialization

Slide 52

Slide 52 text

Server Json Android App Java Gson github.com/google/gson

Slide 53

Slide 53 text

Creating the data model (POJO)

Slide 54

Slide 54 text

"venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 55

Slide 55 text

class Venue { } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 56

Slide 56 text

class Venue { String id; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 57

Slide 57 text

class Venue { String id; String name; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 58

Slide 58 text

class Venue { String id; String name; ContactInfo contact; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 59

Slide 59 text

class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 60

Slide 60 text

class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 61

Slide 61 text

class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo; float rating; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 62

Slide 62 text

class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo; float rating; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 63

Slide 63 text

class Venue { String id; String name; @SerializedName("contact") ContactInfo contactInfo; String photoUrl; } class ContactInfo { String phone; String formattedPhone; } "venue": { "id":"56d92e05498e6c54b6325b19", "name": "Zepra", "contact": { "phone": "036240044", "formattedPhone":"03-624-0044" } "rating": 9.5, "hours": {...} , "photoUrl": "........" }

Slide 64

Slide 64 text

Questions?

Slide 65

Slide 65 text

{"items":[{"reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id ":"4b488bfff964a520184f26e3","name":"Anita La Mamma Del Gelato (הטינא)","contact":{"phone":"+97235170505","formattedPhone":"+972 3-517-0505"},"location":{"address":"42 Shabazi St","crossStreet":"at Pines St","lat":32.06274494279335,"lng":34.76648985707776,"labeledLatLngs":[{"label":" display","lat":32.06274494279335,"lng":34.76648985707776}],"postalCode":"65150", "cc":"IL","city":"ופי-ביבא לת","state":"ביבא לת","country":" לארשי","formattedAddress":["42 Shabazi St (at Pines St)","","65150 ופי-ביבא לת לארשי"]},"categories":[{"id":"4bf58dd8d48988d1c9941735","name":"Ice Cream Shop","pluralName":"Ice Cream Shops","shortName":"Ice Cream","icon":{"prefix":"https://ss3.4sqi.net/img/categories_v2/food/icecream_", "suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":1941 ,"usersCount":1192,"tipCount":78},"url":"http://www.anitaglida.co.il","price":{" tier":1,"message":"Cheap","currency":"$"},"rating":9.5,"ratingColor":"00B551","r atingSignals":310,"allowMenuUrlEdit":true,"beenHere":{"count":0,"marked":false," lastCheckinExpiredAt":0},"hours":{"status":"Open until 12:30 AM","richStatus":{"entities":[],"text":"Open until 12:30

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

class VenuesResponse { List groups; class Group { List items; } class Item { Venue venue; } }

Slide 68

Slide 68 text

Gson gson = new Gson(); venuePojo = gson.fromJson(venueJson, Venue.class); venueJson = gson.toJson(venuePojo);

Slide 69

Slide 69 text

Server Json Android App Java Retrofit GSON Converter

Slide 70

Slide 70 text

Convertors ● Gson: com.squareup.retrofit2:converter-gson ● Jackson: com.squareup.retrofit2:converter-jackson ● Moshi: com.squareup.retrofit2:converter-moshi ● Protobuf: com.squareup.retrofit2:converter-protobuf ● Wire: com.squareup.retrofit2:converter-wire ● Simple XML: com.squareup.retrofit2:converter-simplexml ● Scalars: com.squareup.retrofit2:converter-scalars

Slide 71

Slide 71 text

Make the request already!!

Slide 72

Slide 72 text

How to perform a network request? 1. Ask permission

Slide 73

Slide 73 text

How to perform a network request? 1. Ask permission 2. Setup the Service Generator

Slide 74

Slide 74 text

static final String BASE_URL = "https://api.foursquare.com/v2/"; ServiceGenerator.java

Slide 75

Slide 75 text

static final String BASE_URL = "https://api.foursquare.com/v2/"; static Retrofit.Builder retrofitBuilder = new Retrofit.Builder() ServiceGenerator.java

Slide 76

Slide 76 text

static final String BASE_URL = "https://api.foursquare.com/v2/"; static Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(BASE_URL) ServiceGenerator.java

Slide 77

Slide 77 text

static final String BASE_URL = "https://api.foursquare.com/v2/"; static Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()); ServiceGenerator.java

Slide 78

Slide 78 text

Http Client OKHttp square.github.io/okhttp

Slide 79

Slide 79 text

static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); ServiceGenerator.java

Slide 80

Slide 80 text

static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); static Retrofit retrofit = retrofitBuilder .client(httpClient.build()) .build(); ServiceGenerator.java

Slide 81

Slide 81 text

Question: why are ServiceGenerator fields are static?

Slide 82

Slide 82 text

How to perform a network request? 1. Ask permission 2. Setup the Service Generator 3. Create the response data model

Slide 83

Slide 83 text

class VenuesResponse { List groups; class Group { List items; } class Item { Venue venue; } } Rem inder

Slide 84

Slide 84 text

How to perform a network request? 1. Ask permission 2. Setup the Service Generator 3. Create the response data model 4. Create the service interface

Slide 85

Slide 85 text

@GET("venues/explore") Call getVenues(@Query("ll") String location); public interface FoursquareService Rem inder

Slide 86

Slide 86 text

How to perform a network request? 1. Ask permission 2. Setup the Service Generator 3. Create the response data model 4. Create the service interface 5. Perform Call!

Slide 87

Slide 87 text

FoursquareService foursquareService = ServiceGenerator.retrofit .create(FoursquareService.class);

Slide 88

Slide 88 text

FoursquareService foursquareService = ServiceGenerator.createService(FoursquareService.class); Call call = foursquareService.getVenues(location);

Slide 89

Slide 89 text

call.enqueue(callback); Asynchronous

Slide 90

Slide 90 text

callback = new Callback() { };

Slide 91

Slide 91 text

callback = new Callback() { @Override public void onResponse(Call call, Response response) { VenuesResponse data = response.body(); adapter.setItems(data); } };

Slide 92

Slide 92 text

callback = new Callback() { @Override public void onResponse(Call call, Response response) { VenuesResponse data = response.body(); //handle response data } @Override public void onFailure(...) { //handle failure } };

Slide 93

Slide 93 text

VenuesResponse venuesResponse = call.execute().body(); Synchronous

Slide 94

Slide 94 text

VenuesAdapter.java - (Example) public void onBindViewHolder(VenueViewHolder holder, int position) { textView.setText( venues.get(position).getName()); }

Slide 95

Slide 95 text

No content

Slide 96

Slide 96 text

Questions?

Slide 97

Slide 97 text

Load images!

Slide 98

Slide 98 text

Challenges 1. Heavy 2. Out of memory (Exception) 3. Caching 4. Resize 5. Image manipulation (round corners…)

Slide 99

Slide 99 text

Picasso http://square.github.io/picasso/

Slide 100

Slide 100 text

Server Json Android App Java Picasso OkHttp

Slide 101

Slide 101 text

build.gradle() dependencies { //... implementation 'com.squareup.picasso:picasso:2.5.2' }

Slide 102

Slide 102 text

Picasso .with(context) .load(url) .into(view);

Slide 103

Slide 103 text

VenuesAdapter.java - (Example) public void onBindViewHolder(VenueViewHolder holder, int position){ textView.setText(venues.get(position).getName()); }

Slide 104

Slide 104 text

VenuesAdapter.java - (Example) public void onBindViewHolder(VenueViewHolder holder, int position){ textView.setText(venues.get(position).getName()); if (! TextUtils.isEmpty(venue.getImageUrl())) { } }

Slide 105

Slide 105 text

VenuesAdapter.java - (Example) public void onBindViewHolder(VenueViewHolder holder, int position){ textView.setText(venues.get(position).getName()); if (! TextUtils.isEmpty(venue.getImageUrl())) { Picasso.with(imageView.getContext()) .load(venue.getImageUrl()) .into(imageView); } }

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

We did it!!!

Slide 108

Slide 108 text

Network Profiler

Slide 109

Slide 109 text

No content

Slide 110

Slide 110 text

Network Traffic Tool https://developer.android.com/studio/profile/ddms.html

Slide 111

Slide 111 text

Facebook Stetho https://code.facebook.com/posts/393927910787513/stetho-a-new-debugging-platform-for-android/

Slide 112

Slide 112 text

No content

Slide 113

Slide 113 text

Interceptors [Bonus]

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

static HttpLoggingInterceptor logging = new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(logging) .addNetworkInterceptor(logging) //... ServiceGenerator.java

Slide 116

Slide 116 text

Interceptor apiKeyInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { } ServiceGenerator.java

Slide 117

Slide 117 text

Interceptor apiKeyInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); } ServiceGenerator.java

Slide 118

Slide 118 text

Interceptor apiKeyInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); HttpUrl originalHttpUrl = original.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("client_id",CLIENT_ID) .addQueryParameter("client_secret",CLIENT_SECRET) .build(); ServiceGenerator.java

Slide 119

Slide 119 text

... Request.Builder requestBuilder = original.newBuilder().url(url); return chain.proceed(requestBuilder.build()); } ServiceGenerator.java

Slide 120

Slide 120 text

httpClient.addInterceptor(logging) .addInterceptor(apiKeyInterceptor) //... ServiceGenerator.java

Slide 121

Slide 121 text

Questions?

Slide 122

Slide 122 text

Source code for the demo [read the ReadMe first :) ] https://goo.gl/WfnSpd

Slide 123

Slide 123 text

Thank you

Slide 124

Slide 124 text

Exercise goo.gl/BGPzkt