Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
HTTP Client &
Web Service on Android
Mobile
Application Development
Web Services
HTTP Operation
Web Services
HTTP Operation
There are 2 types of common operation in HTTP
GET : Requests data from a specified resource
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with
sensitive data
GET requests have length restrictions
GET requests should be used only to retrieve data
Web Services
HTTP Operation
There are 2 types of common operation in HTTP
POST : Submits data to be processed to a specified resource
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
Web ServicesIntrodution to
Web Service
Web Services
Today’s Web
Web designed for application to human interactions
Served very well its purpose :
Information sharing : a distributed content library
Enabled B2C e-commerce
Non-automated B2B interactions
How did it happens
Built on very few standards : http + html
Shallow interaction model : very few assumptions made about computing platforms
Result was ubiquity
Web Services
What’s Next ?
The Web is everywhere, there is a lot more we can do !
E-marketplaces
Open, automated B2B e-commerce
Business process integration on the Web
Resource sharing, distributed computing
Current approach is ad-hoc on top of existing standards.
e.g., application-to-application interactions with HTML forms
Goal :
Enabling systematic application-to-application interaction on the Web Web Service was born !
Web Services
What is Web Service ?
UDDI Consortium
Web services are self-contained, modular business applications that have open, Internet-oriented, standards-based interfaces
W3C
A web service is a software application identified by a URI, whose interfaces and bindings are capable of being defined,described and discovered as XML
A web service supports direct interactions with other software agents using XML-based messages exchanged via Internet-based protocols
So in short, we can said the web service is :
A software system designed to support interoperable machine-to-machine interaction over a network
Web Services
Why Web Service ?
Exposing the Existing Function on the network
Web services allows you to expose the functionality of your existing code over the network. Once it is exposed on the network, other application can use the functionality of your program.
Interoperability
Web services allow various applications to talk to each other and share data and services among themselves. For example, a VB or .NET application can talk to Java web services and vice versa
Standardized Protocol
Web services use standardized industry standard protocol for the communication.
Low Cost of Communication
Web services use SOAP over HTTP protocol, so you can use your existing low-cost internet for implementing web services.
Web ServicesWeb Service
Framework
Web Services
Web Service Architecture
In short, WS architecture can be described in terms of :
What goes “on the wire” :
Formats and protocols
What describes what goeson the wire :
Description languages
What allows us to find thesedescriptions :
Discovery of services
Web Services
WSA
Web Service Description Language
Describes the Web Service and defines the functions that are exposed in the Web Service
Universal Description, Discovery and Integration
UDDI is used to register and look up services with a central registry
Web Service Format
Format and protocol that used in web service communication
Web Services
WSA : WSDL
Provides functional description of network services
IDL description
Protocol and deployment details
Platform independent description
Extensible language
Structure :
portType
Abstract definition of a service(set of operations)
Multiple bindings per portType:
How to access it
SOAP, JMS, direct call
Ports
Where to access it
Service
Port(e.g. http://host/svc)
Binding(e.g. SOAP)
Abstract interface
portType
operation(s)
inMesage outMessage
Port
Binding
Web Services
WSA : UDDI
UDDI defines the operation of a service registry:
Data structures for registering
Businesses
Technical specifications : tModel is a keyed reference to a technical specification
Service and service endpoints: referencing the supported tModels
Rules for the operation of a global registry
“private” UDDI nodes are likely to appear, though
Web Services
WSA : UDDI
Web Service
Web Service
SIC CODENAICS
DUNS NumbersThomas Registry ID
Rosetta-NetBASDA
Simple.Buy
Schemas,
Interchange specification
businessEntitybusinessEntitybusinessEntity
businessServicebusinessService
bindingTemplatebindingTemplate
InstanceDetailsInstanceDetails
categoryBag
keyedReferencekeyedReference
identifierBag
keyedReferencekeyedReference
tModels
Web Services
WSA : Format & Protocol
There are some well-known WS formats & protocols that used in web service technology
SOAP
REST
BEEP
E-Business XML
Hessian
XINS
XLANG
The 2 most popular formats
Assignment• Find the definition and concept of
SOAP and REST !
Web ServicesWeb Service
Format &
Protocol
Web Service Format & Protocol
There are 2 most popular web service formats that often used service-based application development
SOAP (Simple Object Access Protocol (SOAP)
REST (REpresentational State Transfer)
SOAP
SOAP (Simple Object Access Protocol)
SOAP is a protocol specification for exchanging structured information in the implementation of web services in computer networks
It uses XML Information Set for its message format, and relies on other application layer protocols, most notably Hypertext Transfer Protocol (HTTP) or Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission
SOAP
SOAP (Simple Object Access Protocol)
SOAP basically using XML formatted message to perform data communication
XML message structure
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format which is both human-readable and machine-readable
It is defined by the W3C
http://www.w3schools.com/xml/
https://en.wikipedia.org/wiki/XML_Schema_(W3C)
SOAP Example
OpenWeatherMapAPI : XML mode
http://openweathermap.org/
Try type or click and open this address in your web browser !
http://api.openweathermap.org/data/2.5/weather?q=Malang&mode=xml&appid=2de143494c0b295cca9337e1e96b00e0
REST
REST (REpresentational State Transfer)
Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web
In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web
In the REST architectural style you can use XML or JSON message to perform data communication, but usually we prefer to use JSON because it’s more lightweight than XML
REST Example
OpenWeatherMapAPI : JSON mode
http://openweathermap.org/
Try type or click and open this address in your web browser !
http://api.openweathermap.org/data/2.5/weather?q=Malang&mode=json&appid=2de143494c0b295cca9337e1e96b00e0
XML vs JSON
Web Services
Incorporating
Web Services in
Android Mobile
Applications
Web Services
Web Services in Mobile Apps
Many Web Services and APIs were originally developed with server to server or server to browser in mind, not mobile applications
Mobile platforms have their own set of challenges given :
Bandwidth
Memory and CPU Availability
Storage Capacity
Connectivity Options and Issues
Security
User Interaction and Display
REST + JSONis better !
Web Services
Web Services in Android
Android has ability to consume HTTP web service response using some methods
Using HTTPClient from Apache package Deprecated since API Ver. 14
HttpURLConnection from Java Net package
Another HTTP API
After HTTPClient deprecated, Google suggest to use HttpUrlConnection instead (Android Documentation)
Web ServicesAndroid HTTP
Consume
Example
Basic Example : Grabbing Image from Web
Web Services
Grabbing Image from Web
Activity_get_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<Button
android:text="Download Content"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Web Services
Grabbing Image from Web
HTTPConnection.java
public class HTTPConnection {
public InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;}}
Web Services
Grabbing Image from Web
GetImageActivity.java
public class GetImageActivity extends Activity {
HTTPConnection conn = new HTTPConnection();
String imageURL = "http://file.filkom.ub.ac.id/fileupload/assets/
upload/file/PTIIK/konten/2014-10/pimpinan.jpg";
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... url) {
// ---download an image---
Bitmap bitmap = DownloadImage(url[0]);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
}
Web Services
Grabbing Image from Web
GetImageActivity.java (continued)
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = conn.OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
Button btnOpen = (Button) findViewById(R.id.Button01);
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new BackgroundTask().execute(imageURL);
}
});}
Web Services
Grabbing Image from Web
GetImageActivity.java (continued)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_get_image, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}