Lecture-15-WebServices
Lecture-15-WebServices
– This is just like in ordinary HTTP, where a web browser sends an HTTP
request to a web server, and the web server replies with an HTTP
response.
Web Services
• Web Service Message Exchange Patterns.
Web Service Message Formats
• In the beginning the only web service message format
available was SOAP (Simple Object Access Protocol) – an XML
based format.
– Clients can issue request via HTTP methods (e.g, “GET”, “POST”, etc)
http://somedomain.com/profiles/bugsbunny
<profile>
<firstName>Bugs</firstName>
<lastName>Bunny</lastName>
<address>
<street>The Road 123</street>
<zip>12345</zip>
<city>USA</city>
</address>
</profile>
REST + JSON
http://somedomain.com/profiles/bugsbunny
{
firstName : "Bugs",
lastName : "Bunny",
address : {
street : "The Road 123",
zip : "12345",
city : "USA"
}
}
JSON
• JSON (JavaScript Object Notation), is a lightweight text‐based open
standard designed for human‐readable data interchange.
• See: http://json.org/
Sample JSON Representation
{
"person":
[
{
"name":{"first":"John","last":"Adams"},
"age":"40"
},
{
"name":{"first":"Thomas","last":"Jefferson"},
"age":"35"
}
]
}
JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax.
• Contains basic data types: Number, String, Boolean, Object, Array, and
null.
Sample JSON Representation
{
"person":
[
{
"name":{"first":"John","last":"Adams"},
"age":"40"
},
{
"name":{"first":"Thomas","last":"Jefferson"},
"age":"35"
}
]
}
Web Service Providers
• Most online businesses, portals & social networks provide web
services API to developers. Some free web services available to
developers include:
– http://restcountries.eu/
– http://www.freecurrencyconverterapi.com/
– http://openweathermap.org/API
– https://www.mashape.com/
References
• http://en.wikipedia.org/wiki/Web_service
• http://tutorials.jenkov.com/web‐services/index.html
• http://json.org/
• http://en.wikipedia.org/wiki/JSON
CREATING JSON WEB SERVICES
IN PHP
Setting Content Type with Header
• By default, a PHP script's output is assumed to be HTML.
header("Content-type: text/plain");
echo "This output is plain text now!\n";
Content ("MIME") Types
MIME type Related File Extension
text/plain .txt
text/html .html, .htm
text/javascript .js
text/xml .xml
Application/json .json
image/jpeg .jpg, .jpeg
video/quicktime .mov
application/octet‐stream .exe
header("Content-type: text/plain");
$a = $_REQUEST["v1"];
$b = $_REQUEST["v2"];
$result = $a * $b;
echo $result;
Client: Parsing Text
$url="http://localhost/www/web-
development/webservices-rest/server-
multiply.php?v1=3&v2=4";
$result=file_get_contents($url);
if (($_REQUEST["v1"]=="") || ($_REQUEST["v2"]==""))
{
header("HTTP/1/1 400 Invalid Request");
die("An HTTP error 400 (Invalid request) occurred.");
}
HTTP Status Codes
Code Meaning
200 OK
301 Moved
400 Invalid Request
403 Forbidden
404 Not Found
500 Internal Server Error
$json_a=json_decode($string,true);
foreach($json_a[person] as $p)
{
echo "Name: ".$p[name][first]." ".$p[name][last].
"Age: ".$p[age];
}
Parse JSON as an Object
$string='{"person":
. . .
}';
$json_o=json_decode($string);
foreach($json_o->person as $p)
{
echo "Name: ".$p->name->first." ". $p->name->last.
"Age: ".$p->age;
}
Server: Emitting JSON Data
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$json='
{
"person":
[
{
"name":{"first":"John","last":"Adams"},
"age":"40"
},
{
"name":{"first":"Thomas","last":"Jefferson"},
"age":"35"
}
]
}
';
echo $json;
Client: Parse JSON From URL
$url="http://localhost/www/univeristy/awd
/webservices-rest/json-server.php";
$string = file_get_contents($url);
$json_o=json_decode($string);
foreach($json_o->person as $p)
{
echo "Name: ".$p->name->first." ". $p->name->last. "
Age: ".$p->age . "<br />";
}
CONSUMING JSON WEB SERVICES
IN ANDROID APPS
Consuming JSON Web Services
• In order to consume JSON Web Service in our Android Apps:
– Our app needs permission to connect to the Internet.
• We can specify android.permission.INTERNET in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Create Activity
Activity
activity_main.xml
. . .
<Button
android:id="@+id/btnFindInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editCountryName"
android:layout_alignBottom="@+id/editCountryName"
android:layout_toRightOf="@+id/editCountryName"
android:text="@string/btn_get_info"
android:onClick="loadCountryInfo" />
. . .
MainActivity.java
. . .
public void loadCountryInfo(View view) {
if (countryName.length()==0) {
Toast.makeText(this, "No Country Specified", Toast.LENGTH_SHORT).show();
}
else {
new wsAsyncTask().execute(strURL);
}
}
. . .
AsyncTask
• AsyncTask class allows to
if (countryName.length()==0) {
Toast.makeText(this, "No Country Specified", Toast.LENGTH_SHORT).show();
}
else {
new wsAsyncTask().execute(strURL);
}
}
. . .
wsAsyncTask()
. . .
private class wsAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strURL) {
return requestWebService(strURL[0]);
}
@Override
protected void onPostExecute(String result) {
. . .
}
}
. . .
requestWebService()
public static String requestWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
. . .
} catch (MalformedURLException e) {
e.printStackTrace(); // URL is invalid
} catch (SocketTimeoutException e) {
e.printStackTrace(); // data retrieval or connection timed out
} catch (IOException e) {
e.printStackTrace(); // could not read response body
// (could not create input stream)
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
requestWebService()
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(10000);
}
Array JSON Format
http://restcountries.eu/rest/v1/name/Pakistan
Object
[
{ String
. . .
"capital": "Islamabad", Number
. . .
"population": 184845000,
. . . Number
"area": 881912,
. . .
"currencies": [
"PKR" Array
],
. . .
}
]
wsAsyncTask()
. . .
private class wsAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strURL) {
return requestWebService(strURL[0]);
}
@Override
protected void onPostExecute(String result) {
. . .
}
}
. . .
“onPostExecute()” in wsAsyncTask()
protected void onPostExecute(String result) {
txtCapital=(TextView) findViewById(R.id.textCapitalValue);
txtArea=(TextView) findViewById(R.id.textAreaValue);
txtPopulation=(TextView) findViewById(R.id.textPopulationValue);
txtCurrency=(TextView) findViewById(R.id.textCurrencyValue);
try {
JSONArray rootArray=new JSONArray(result);
JSONObject rootObject=rootArray.getJSONObject(0);
txtCapital.setText(rootObject.optString("capital"));
txtArea.setText(rootObject.optString("area"));
txtPopulation.setText(rootObject.optString("population"));
txtCurrency.setText(rootObject.optJSONArray("currencies").getString(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
Using JSON Web Service
Adding Progress Dialog
AsyncTask
MainActivity.java
public class MainActivity extends Activity {
private TextView txtCapital;
private TextView txtArea;
private TextView txtPopulation;
private TextView txtCurrency;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
. . .
Add “onPreExecute()” in wsAsyncTask()
. . .
private class wsAsyncTask extends AsyncTask<String, Void, String> {
. . .
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("Please Wait..");
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
}
}
. . .
Dismiss Dialog in “onPostExecute()”
protected void onPostExecute(String result) {
txtCapital=(TextView) findViewById(R.id.textCapitalValue);
txtArea=(TextView) findViewById(R.id.textAreaValue);
txtPopulation=(TextView) findViewById(R.id.textPopulationValue);
txtCurrency=(TextView) findViewById(R.id.textCurrencyValue);
try {
JSONArray rootArray=new JSONArray(result);
JSONObject rootObject=rootArray.getJSONObject(0);
txtCapital.setText(rootObject.optString("capital"));
txtArea.setText(rootObject.optString("area"));
txtPopulation.setText(rootObject.optString("population"));
txtCurrency.setText(rootObject.optJSONArray("currencies").getString(0));
} catch (JSONException e) {
e.printStackTrace();
}
dialog.dismiss();
}
Using JSON Web Service
Consuming JSON Web Services
• In order to consume JSON Web Service in our Android Apps:
– Our app needs permission to connect to the Internet.
• We can specify android.permission.INTERNET in AndroidManifest.xml
. . .
} catch (MalformedURLException e) {
e.printStackTrace(); // URL is invalid
} catch (SocketTimeoutException e) {
e.printStackTrace(); // data retrieval or connection timed out
} catch (IOException e) {
e.printStackTrace(); // could not read response body
// (could not create input stream)
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
Sending Data With HTTP Request
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(10000);
}
Sending Data With HTTP Request
HttpURLConnection urlConnection = null;
try {
. . .
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setUseCaches (false);
. . .
}
Consuming Web Services on Localhost
• Each instance of the emulator runs behind a virtual
router/firewall service that isolates it from your development
machine's network interfaces and settings and from the
internet.
• http://developer.android.com/tools/devices/emulator.html#emulatornetworking
• https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
• http://developer.android.com/reference/org/json/JSONObject.html
• http://developer.android.com/reference/org/json/JSONArray.html
• http://developer.android.com/reference/android/os/AsyncTask.html
• http://developer.android.com/training/basics/network‐ops/connecting.html
• http://developer.android.com/reference/android/app/ProgressDialog.html