SlideShare une entreprise Scribd logo
1  sur  59
Télécharger pour lire hors ligne
6
 Network &
 Web Services
 Anuchit Chalothorn
 anoochit@gmail.com

Licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Connecting to Network
Note that to perform the network operations
described in this lesson, your application
manifest must include the following permissions:

<uses-permission android:name="android.permission.INTERNET"
/>
<uses-permission android:name="android.permission.
ACCESS_NETWORK_STATE"/>




Ref: http://developer.android.com/training/basics/network-ops/connecting.html
StrictMode
Within an Android application you should avoid
performing long running operations on the user
interface thread. This includes file and network
access. StrictMode allows to setup policies in
your application to avoid doing incorrect things.
Turn StrictMode Off
If you are targeting Android 3.0 or higher, you can turn this
check off via the following code at the beginning of your
onCreate() method of your Activity. (Not recommend)


StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
Manage Network Usage
A device can have various types of network connections.
This lesson focuses on using either a Wi-Fi or a mobile
network connection. To check the network connection, you
typically use the following classes:

● ConnectivityManager: Answers queries about the state of
  network connectivity. It also notifies applications when
  network connectivity changes.
● NetworkInfo: Describes the status of a network interface of a
  given type (currently either Mobile or Wi-Fi).
Check the Network Connection

ConnectivityManager connMgr = (ConnectivityManager)
     getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()){
   // fetch data
} else {
   // display error
}
Workshop: Check network connection
Use snippet from previous slide to check
network connection and notify user.


ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
       NetworkInfo networkInfo = connMgr.
getActiveNetworkInfo();
Network Operations on a Separate Thread

Network operations can involve unpredictable
delays. To prevent this from causing a poor
user experience, always perform network
operations on a separate thread from the UI.
The AsyncTask class provides one of the
simplest ways to fire off a new task from the UI
thread.
AsyncTask
The AsyncTask class provides one of the
simplest ways to fire off a new task from the UI
thread.

private class DownloadWebpageText extends AsyncTask {
  protected String doInBackground(String... urls) {
     ...
  }
}
Workshop: Read text data from web
Read HTML data from web using
HTTPConnection. See snippet in GitHub.
Workshop: Load Image from Web
Read stream binary from web and pass into
ImageView

InputStream in = new URL(url).openStream();
myImage = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(myImage);
Web Services
A web service is a method of communication
between two electronic devices over the World
Wide Web. We can identify two major classes
of Web services
   ● REST-compliant Web services
   ● arbitrary Web services.
SOAP: Old fasion


                                          Yellow Pages                             WSDL
            WSDL




                              WSDL

        Requester                                                                Provider

                                              SOAP




Requester ask or search yellow pages which address and how to talk with provider. The yellow pages
    'll send the response by using WSDL how to talk which provide by Provider to the requester.
            Requester receives the address and methods then communicate with Provider.
Web APIs
A web API is a development in web services
where emphasis has been moving to simpler
representational state transfer (REST) based
communications. RESTful APIs do not require
XML-based web service protocols (SOAP and
WSDL) to support their light-weight interfaces.
API Protocols




Ref: http://java.dzone.com/articles/streaming-apis-json-vs-xml-and
Data Formats




Ref: http://java.dzone.com/articles/streaming-apis-json-vs-xml-and
Say "Goodbye" to XML
RESTFul / REST API
a style of software architecture for distributed
systems such as the WWW. The REST
language uses nouns and verbs, and has an
emphasis on readability. Unlike SOAP, REST
does not require XML parsing and does not
require a message header to and from a
service provider.
Concept
● the base URI for the web service, such as
  http://example.com/resources/
● the Internet media type of the data
  supported by the web service.
● the set of operations supported by the web
  service using HTTP methods (e.g., GET,
  PUT, POST, or DELETE).
● The API must be hypertext driven.
HTTP Request


                 HTTP Request


     Client                          Server



              HTTP Response + Data
                200 OK
                403 Forbidden
                404 Not found
                500 Internal Error
HTTP Request


                 GET /users/anoochit HTTP/1.1


     Requester                                  Provider


                        200 OK + Data
Example URI
● http://example.org/user/
● http://example.org/user/anuchit
● http://search.twitter.com/search.json?q=xxx
Request & Action

Resource                              GET              PUT             POST       DELETE

http://example.org/user        list collection   replace           create       delete

http://example.org/user/rose   list data         replace/ create   ? / create   delete
Mobile App with Web Services


                                                        http request
                               Data       Req



                                                                           Provider


   (2)       (1)
  Data      Parse           Res        Data
                                                         response




     * This is your destiny you cannot change your future, accept using vendor sdk's
Call Web Services

                               GET /user/anoochit

                                                                      REST
     Android
                                                                      Server

                           200 OK with XML or JSON string




●   HTTP request                                            ●   Check request method
●   Method GET, POST, PUT or DELETE                         ●   Parse data from URI
●   Get BufferReader and pack into                          ●   Process
    "String" <= JSON String                                 ●   Return XML or JSON string
●   Parse "String Key"
●   Get your value
No "official" standard

There is no "official" standard for RESTful web
services, This is because REST is an
architectural style, unlike SOAP, which is a
protocol. Even though REST is not a standard,
a RESTful implementation such as the Web
can use standards like HTTP, URI, XML, etc.
RESTful API Design
But you should follow design guideline
● RESTful API Design
● Learn REST
Useful tools
if you want to test your RESTful web service by
sent another method, try this
● Advanced REST Client for Chrome
● JSONView and JSONLint for Chrome
● REST Client for Firefox
JSON Example

{
    "firstname": "Anuchit",
    "lastname": "Chalothorn"
}
JSON Example
[
    {
        "firstname" : "Anuchit",
        "lastname" : "Chalothorn"
    },
    {
        "firstname" : "Sira",
        "lastname" : "Nokyongthong"
    }
]
Android & JSON
JSON is a very condense data exchange
format. Android includes the json.org libraries
which allow to work easily with JSON files.
JSON Object Parsing

JSONObject c = new JSONObject(json);
String firstname=c.get("firstname").toString();
String lastname=c.get("lastname").toString();
JSON Array Parsing

JSONArray data = new JSONArray(json);
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String firstname = c.getString("firstname");
String lastname = c.getString("lastname");
}
Simple RESTful with PHP
You can make a simple RESTful API with PHP
for routing, process and response JSON data.
The following tools you should have;
● Web Server with PHP support
● PHP Editor
● REST Client plugin for browser
Workshop: JSON with PHP
PHP has a function json_encode to generate
JSON data from mix value. Create an App to
read JSON data in a web server.


header('Content-Type: application/json;
charset=utf-8');
$data = array("msg"=>"Hello World JSON");
echo json_encode($data);
Workshop: JSON with PHP
Create multi-dimensional array the pass to json
function to make a JSON Array data

$data=array(
   array("firstname"=>"Anuchit",
         "lastname"=>"Chalothorn"),
   array("firstname"=>"Sira",
         "lastname"=>"Nokyongthong")
);
Workshop: Check request methods
PHP has $_SERVER variable to check HTTP
request methods of each request from client, so
you can check request from this variable.

$method = $_SERVER["REQUEST_METHOD"];
switch($method){
    case "GET":
        break;
    ...
}
RESTful Design
Now we can check request from client, now we
can follow the RESTful design guideline. You
may use htaccess to make a beautiful URL.

  http://hostname/v1/contact/data

         service version number   resource   data
Call RESTful API

                               GET /user/anoochit

                                                                      REST
     Android
                                                                      Server

                           200 OK with XML or JSON string




●   HTTP request                                            ●   Check request method
●   Method GET, POST, PUT or DELETE                         ●   Parse data from URI
●   Get BufferReader and pack into                          ●   Process
    "String" <= JSON String                                 ●   Return XML or JSON string
●   Parse "String Key"
●   Get your value
Workshop: Simple RESTful
Make RESTful service of this
● Echo your name
  ○ sent your name with POST method and response
    with JSON result
● Asking for date and time
  ○ sent GET method response with JSON result
● Temperature unit converter
  ○ sent a degree number and type of unit with
    POST method and response JSON result
Workshop: RESTful Echo

$data = array("result"=>
              "Hello, ".$_POST["name"]);
echo json_encode($data);
Workshop: RESTful Date Time

$data = array("result"=>
               date("d M Y H:i:s"));
echo json_encode($data);
Workshop: RESTful Temperature
if ($_POST["type"]=="c") {
   $result=(($_POST["degree"]-32)*5)/9;
} else {
   $result=(($_POST["degree"]*9)/5)+32;
}
$data = array("result"=>$result));
echo json_encode($data);
Workshop: App REST Echo
Make a mobile app call REST Echo API using
Http Post method to send value.
Workshop: App REST Temperature
Make a mobile app call REST temperature unit
converter API, using Http Post method to send
a degree value and unit type to convert.
Workshop: App REST Date Time
Make a mobile app call REST date time, using
Http Get method to get a value of date and
time.
End

Contenu connexe

Tendances

JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Introduction to RESTful Web Services
Introduction to RESTful Web ServicesIntroduction to RESTful Web Services
Introduction to RESTful Web ServicesFelipe Dornelas
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryFulvio Corno
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionseyelliando dias
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 
Principles of building effective REST API
Principles of building effective REST APIPrinciples of building effective REST API
Principles of building effective REST APIGeorgy Podsvetov
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SASTBlueinfy Solutions
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallPeter R. Egli
 
Services web RESTful
Services web RESTfulServices web RESTful
Services web RESTfulgoldoraf
 

Tendances (20)

Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
RIA and Ajax
RIA and AjaxRIA and Ajax
RIA and Ajax
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Introduction to RESTful Web Services
Introduction to RESTful Web ServicesIntroduction to RESTful Web Services
Introduction to RESTful Web Services
 
OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Ajax
AjaxAjax
Ajax
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP library
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Principles of building effective REST API
Principles of building effective REST APIPrinciples of building effective REST API
Principles of building effective REST API
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Ws rest
Ws restWs rest
Ws rest
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SAST
 
Intoduction to php web services and json
Intoduction to php  web services and jsonIntoduction to php  web services and json
Intoduction to php web services and json
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure Call
 
Services web RESTful
Services web RESTfulServices web RESTful
Services web RESTful
 

En vedette

Sintesis informativa 20 11 2012
Sintesis informativa 20 11 2012Sintesis informativa 20 11 2012
Sintesis informativa 20 11 2012megaradioexpress
 
Unidad i, ii y iii y iv herramientas (1)
Unidad i, ii y iii y iv herramientas (1)Unidad i, ii y iii y iv herramientas (1)
Unidad i, ii y iii y iv herramientas (1)bety ruiz
 
Sustainability report 2009
Sustainability report 2009Sustainability report 2009
Sustainability report 2009Hera Group
 
Ponencia Clarke, Modet & Cº - Reunión RedOTRI 2014
Ponencia Clarke, Modet & Cº -  Reunión RedOTRI 2014Ponencia Clarke, Modet & Cº -  Reunión RedOTRI 2014
Ponencia Clarke, Modet & Cº - Reunión RedOTRI 2014OTRI - Universidad de Granada
 
PERI-Facts.11.2.11
PERI-Facts.11.2.11PERI-Facts.11.2.11
PERI-Facts.11.2.11Bob Latino
 
Fuerzas armadas revolucionarias de colombia
Fuerzas armadas revolucionarias de colombiaFuerzas armadas revolucionarias de colombia
Fuerzas armadas revolucionarias de colombiaGabiC uebi_3A
 
Puebla Soy Del Pueblo
Puebla Soy Del PuebloPuebla Soy Del Pueblo
Puebla Soy Del Pueblomusikari
 
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02Stacey Guerrero Moral
 
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...mStoner, Inc.
 
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...Leonardo Triana
 
Molecular tools for pet of human depression ok 080513
Molecular tools for pet of human depression ok 080513Molecular tools for pet of human depression ok 080513
Molecular tools for pet of human depression ok 080513dfsmithdfsmith
 
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)MercadoShops de MercadoLibre
 

En vedette (20)

Equipo5
Equipo5Equipo5
Equipo5
 
Sintesis informativa 20 11 2012
Sintesis informativa 20 11 2012Sintesis informativa 20 11 2012
Sintesis informativa 20 11 2012
 
Unidad i, ii y iii y iv herramientas (1)
Unidad i, ii y iii y iv herramientas (1)Unidad i, ii y iii y iv herramientas (1)
Unidad i, ii y iii y iv herramientas (1)
 
Jara egaf11
Jara egaf11Jara egaf11
Jara egaf11
 
Sustainability report 2009
Sustainability report 2009Sustainability report 2009
Sustainability report 2009
 
Ponencia Clarke, Modet & Cº - Reunión RedOTRI 2014
Ponencia Clarke, Modet & Cº -  Reunión RedOTRI 2014Ponencia Clarke, Modet & Cº -  Reunión RedOTRI 2014
Ponencia Clarke, Modet & Cº - Reunión RedOTRI 2014
 
PERI-Facts.11.2.11
PERI-Facts.11.2.11PERI-Facts.11.2.11
PERI-Facts.11.2.11
 
Business Writing Course
Business Writing CourseBusiness Writing Course
Business Writing Course
 
Cantábrico Traducciones
Cantábrico TraduccionesCantábrico Traducciones
Cantábrico Traducciones
 
Company Profile - 2015
Company Profile - 2015Company Profile - 2015
Company Profile - 2015
 
Fuerzas armadas revolucionarias de colombia
Fuerzas armadas revolucionarias de colombiaFuerzas armadas revolucionarias de colombia
Fuerzas armadas revolucionarias de colombia
 
Desarrolloorganizacionalexposicin 111019104022-phpapp02
Desarrolloorganizacionalexposicin 111019104022-phpapp02Desarrolloorganizacionalexposicin 111019104022-phpapp02
Desarrolloorganizacionalexposicin 111019104022-phpapp02
 
Puebla Soy Del Pueblo
Puebla Soy Del PuebloPuebla Soy Del Pueblo
Puebla Soy Del Pueblo
 
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02
Mdulodeviciosdellenguaje1sem 2011-120430224940-phpapp02
 
Copias Publicitarias
Copias PublicitariasCopias Publicitarias
Copias Publicitarias
 
Competencia y Compras Públicas
Competencia y  Compras PúblicasCompetencia y  Compras Públicas
Competencia y Compras Públicas
 
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...
Best Practices in Social Media: Summary of Findings from the Fifth Comprehens...
 
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...
Wewe, una comunidad para transformar el mundo a traves de la ciencia y la tec...
 
Molecular tools for pet of human depression ok 080513
Molecular tools for pet of human depression ok 080513Molecular tools for pet of human depression ok 080513
Molecular tools for pet of human depression ok 080513
 
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)
Cómo delegar tu dominio a MercadoShops con GoDaddy (Argentina)
 

Similaire à Android App Development 06 : Network &amp; Web Services

Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IAnuchit Chalothorn
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1Aleh Struneuski
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuseejlp12
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 

Similaire à Android App Development 06 : Network &amp; Web Services (20)

Web Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day IWeb Service and Mobile Integrated Day I
Web Service and Mobile Integrated Day I
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Automated testing web services - part 1
Automated testing web services - part 1Automated testing web services - part 1
Automated testing web services - part 1
 
RESTful web service with JBoss Fuse
RESTful web service with JBoss FuseRESTful web service with JBoss Fuse
RESTful web service with JBoss Fuse
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
API
APIAPI
API
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 

Plus de Anuchit Chalothorn (20)

Flutter Workshop 2021 @ ARU
Flutter Workshop 2021 @ ARUFlutter Workshop 2021 @ ARU
Flutter Workshop 2021 @ ARU
 
Flutter workshop @ bang saen 2020
Flutter workshop @ bang saen 2020Flutter workshop @ bang saen 2020
Flutter workshop @ bang saen 2020
 
13 web service integration
13 web service integration13 web service integration
13 web service integration
 
09 material design
09 material design09 material design
09 material design
 
07 intent
07 intent07 intent
07 intent
 
05 binding and action
05 binding and action05 binding and action
05 binding and action
 
04 layout design and basic widget
04 layout design and basic widget04 layout design and basic widget
04 layout design and basic widget
 
03 activity life cycle
03 activity life cycle03 activity life cycle
03 activity life cycle
 
02 create your first app
02 create your first app02 create your first app
02 create your first app
 
01 introduction
01 introduction 01 introduction
01 introduction
 
Material Theme
Material ThemeMaterial Theme
Material Theme
 
00 Android Wear Setup Emulator
00 Android Wear Setup Emulator00 Android Wear Setup Emulator
00 Android Wear Setup Emulator
 
MongoDB Replication Cluster
MongoDB Replication ClusterMongoDB Replication Cluster
MongoDB Replication Cluster
 
MongoDB Shard Cluster
MongoDB Shard ClusterMongoDB Shard Cluster
MongoDB Shard Cluster
 
IT Automation with Chef
IT Automation with ChefIT Automation with Chef
IT Automation with Chef
 
IT Automation with Puppet Enterprise
IT Automation with Puppet EnterpriseIT Automation with Puppet Enterprise
IT Automation with Puppet Enterprise
 
Using PhoneGap Command Line
Using PhoneGap Command LineUsing PhoneGap Command Line
Using PhoneGap Command Line
 
Collaborative development with Git | Workshop
Collaborative development with Git | WorkshopCollaborative development with Git | Workshop
Collaborative development with Git | Workshop
 
OpenStack Cheat Sheet V2
OpenStack Cheat Sheet V2OpenStack Cheat Sheet V2
OpenStack Cheat Sheet V2
 
REST API with CakePHP
REST API with CakePHPREST API with CakePHP
REST API with CakePHP
 

Android App Development 06 : Network &amp; Web Services

  • 1. 6 Network & Web Services Anuchit Chalothorn anoochit@gmail.com Licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
  • 2. Connecting to Network Note that to perform the network operations described in this lesson, your application manifest must include the following permissions: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission. ACCESS_NETWORK_STATE"/> Ref: http://developer.android.com/training/basics/network-ops/connecting.html
  • 3. StrictMode Within an Android application you should avoid performing long running operations on the user interface thread. This includes file and network access. StrictMode allows to setup policies in your application to avoid doing incorrect things.
  • 4. Turn StrictMode Off If you are targeting Android 3.0 or higher, you can turn this check off via the following code at the beginning of your onCreate() method of your Activity. (Not recommend) StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
  • 5. Manage Network Usage A device can have various types of network connections. This lesson focuses on using either a Wi-Fi or a mobile network connection. To check the network connection, you typically use the following classes: ● ConnectivityManager: Answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. ● NetworkInfo: Describes the status of a network interface of a given type (currently either Mobile or Wi-Fi).
  • 6. Check the Network Connection ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo=connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()){ // fetch data } else { // display error }
  • 7. Workshop: Check network connection Use snippet from previous slide to check network connection and notify user. ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr. getActiveNetworkInfo();
  • 8.
  • 9. Network Operations on a Separate Thread Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread.
  • 10. AsyncTask The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. private class DownloadWebpageText extends AsyncTask { protected String doInBackground(String... urls) { ... } }
  • 11. Workshop: Read text data from web Read HTML data from web using HTTPConnection. See snippet in GitHub.
  • 12.
  • 13.
  • 14. Workshop: Load Image from Web Read stream binary from web and pass into ImageView InputStream in = new URL(url).openStream(); myImage = BitmapFactory.decodeStream(in); imageView.setImageBitmap(myImage);
  • 15.
  • 16. Web Services A web service is a method of communication between two electronic devices over the World Wide Web. We can identify two major classes of Web services ● REST-compliant Web services ● arbitrary Web services.
  • 17. SOAP: Old fasion Yellow Pages WSDL WSDL WSDL Requester Provider SOAP Requester ask or search yellow pages which address and how to talk with provider. The yellow pages 'll send the response by using WSDL how to talk which provide by Provider to the requester. Requester receives the address and methods then communicate with Provider.
  • 18. Web APIs A web API is a development in web services where emphasis has been moving to simpler representational state transfer (REST) based communications. RESTful APIs do not require XML-based web service protocols (SOAP and WSDL) to support their light-weight interfaces.
  • 22. RESTFul / REST API a style of software architecture for distributed systems such as the WWW. The REST language uses nouns and verbs, and has an emphasis on readability. Unlike SOAP, REST does not require XML parsing and does not require a message header to and from a service provider.
  • 23. Concept ● the base URI for the web service, such as http://example.com/resources/ ● the Internet media type of the data supported by the web service. ● the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE). ● The API must be hypertext driven.
  • 24. HTTP Request HTTP Request Client Server HTTP Response + Data 200 OK 403 Forbidden 404 Not found 500 Internal Error
  • 25. HTTP Request GET /users/anoochit HTTP/1.1 Requester Provider 200 OK + Data
  • 26. Example URI ● http://example.org/user/ ● http://example.org/user/anuchit ● http://search.twitter.com/search.json?q=xxx
  • 27. Request & Action Resource GET PUT POST DELETE http://example.org/user list collection replace create delete http://example.org/user/rose list data replace/ create ? / create delete
  • 28. Mobile App with Web Services http request Data Req Provider (2) (1) Data Parse Res Data response * This is your destiny you cannot change your future, accept using vendor sdk's
  • 29. Call Web Services GET /user/anoochit REST Android Server 200 OK with XML or JSON string ● HTTP request ● Check request method ● Method GET, POST, PUT or DELETE ● Parse data from URI ● Get BufferReader and pack into ● Process "String" <= JSON String ● Return XML or JSON string ● Parse "String Key" ● Get your value
  • 30. No "official" standard There is no "official" standard for RESTful web services, This is because REST is an architectural style, unlike SOAP, which is a protocol. Even though REST is not a standard, a RESTful implementation such as the Web can use standards like HTTP, URI, XML, etc.
  • 31. RESTful API Design But you should follow design guideline ● RESTful API Design ● Learn REST
  • 32. Useful tools if you want to test your RESTful web service by sent another method, try this ● Advanced REST Client for Chrome ● JSONView and JSONLint for Chrome ● REST Client for Firefox
  • 33. JSON Example { "firstname": "Anuchit", "lastname": "Chalothorn" }
  • 34. JSON Example [ { "firstname" : "Anuchit", "lastname" : "Chalothorn" }, { "firstname" : "Sira", "lastname" : "Nokyongthong" } ]
  • 35. Android & JSON JSON is a very condense data exchange format. Android includes the json.org libraries which allow to work easily with JSON files.
  • 36. JSON Object Parsing JSONObject c = new JSONObject(json); String firstname=c.get("firstname").toString(); String lastname=c.get("lastname").toString();
  • 37.
  • 38. JSON Array Parsing JSONArray data = new JSONArray(json); for (int i = 0; i < data.length(); i++) { JSONObject c = data.getJSONObject(i); String firstname = c.getString("firstname"); String lastname = c.getString("lastname"); }
  • 39.
  • 40. Simple RESTful with PHP You can make a simple RESTful API with PHP for routing, process and response JSON data. The following tools you should have; ● Web Server with PHP support ● PHP Editor ● REST Client plugin for browser
  • 41. Workshop: JSON with PHP PHP has a function json_encode to generate JSON data from mix value. Create an App to read JSON data in a web server. header('Content-Type: application/json; charset=utf-8'); $data = array("msg"=>"Hello World JSON"); echo json_encode($data);
  • 42.
  • 43. Workshop: JSON with PHP Create multi-dimensional array the pass to json function to make a JSON Array data $data=array( array("firstname"=>"Anuchit", "lastname"=>"Chalothorn"), array("firstname"=>"Sira", "lastname"=>"Nokyongthong") );
  • 44.
  • 45. Workshop: Check request methods PHP has $_SERVER variable to check HTTP request methods of each request from client, so you can check request from this variable. $method = $_SERVER["REQUEST_METHOD"]; switch($method){ case "GET": break; ... }
  • 46.
  • 47. RESTful Design Now we can check request from client, now we can follow the RESTful design guideline. You may use htaccess to make a beautiful URL. http://hostname/v1/contact/data service version number resource data
  • 48. Call RESTful API GET /user/anoochit REST Android Server 200 OK with XML or JSON string ● HTTP request ● Check request method ● Method GET, POST, PUT or DELETE ● Parse data from URI ● Get BufferReader and pack into ● Process "String" <= JSON String ● Return XML or JSON string ● Parse "String Key" ● Get your value
  • 49. Workshop: Simple RESTful Make RESTful service of this ● Echo your name ○ sent your name with POST method and response with JSON result ● Asking for date and time ○ sent GET method response with JSON result ● Temperature unit converter ○ sent a degree number and type of unit with POST method and response JSON result
  • 50. Workshop: RESTful Echo $data = array("result"=> "Hello, ".$_POST["name"]); echo json_encode($data);
  • 51. Workshop: RESTful Date Time $data = array("result"=> date("d M Y H:i:s")); echo json_encode($data);
  • 52. Workshop: RESTful Temperature if ($_POST["type"]=="c") { $result=(($_POST["degree"]-32)*5)/9; } else { $result=(($_POST["degree"]*9)/5)+32; } $data = array("result"=>$result)); echo json_encode($data);
  • 53. Workshop: App REST Echo Make a mobile app call REST Echo API using Http Post method to send value.
  • 54.
  • 55. Workshop: App REST Temperature Make a mobile app call REST temperature unit converter API, using Http Post method to send a degree value and unit type to convert.
  • 56.
  • 57. Workshop: App REST Date Time Make a mobile app call REST date time, using Http Get method to get a value of date and time.
  • 58.
  • 59. End