Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Consuming Webservices - Weather Demo
/*
This code is Based on example given by M. Murphy CommonsWare, LLC
"The Busy Coder's Guide To Android Development" V3.4 Chapter 29.
App has been modified to get the weather forecast of a particular
location (no GPS). The elements included in the response object
are briefly shown as an array of nodes.
*/
package com.commonsware.android.internet;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import
import
import
import
import
import
import
import
import
org.apache.http.client.HttpClient;
org.apache.http.client.ResponseHandler;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.BasicResponseHandler;
org.apache.http.impl.client.DefaultHttpClient;
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.NodeList;
org.xml.sax.InputSource;
import
import
import
import
import
import
import
android.app.Activity;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.os.Bundle;
android.util.Log;
android.webkit.WebView;
public class WeatherDemo extends Activity {
private
private
private
private
String format;
WebView browser;
HttpClient client;
List<Forecast> forecasts = new ArrayList<Forecast>();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
format = getString(R.string.url);
browser = (WebView) findViewById(R.id.webkit);
client = new DefaultHttpClient();
url value is :
http://www.weather.gov/forecasts/xml/sample_
products/browser_interface/ndfdXMLclient.php
?&lat=%1$f&lon=%2$f&product=time
-series&begin=2011-0101T00:00:00&end=2016-1231T00:00:00&temp=temp&icons=icons
}
@Override
public void onResume() {
super.onResume();
// provide coordinates of a given location
Location loc = new Location("CLEVELAND AERA");
loc.setLatitude(41.4797);
loc.setLongitude(-81.6785);
updateForecast(loc);
}
1
private void updateForecast(Location loc) {
//obtaining forecast for given region
String url = String.format(format,
loc.getLatitude(),
loc.getLongitude());
Log.e("URL value: ", url );
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(getMethod, responseHandler);
buildForecasts(responseBody);
String page = generatePage();
browser.loadDataWithBaseURL(null, page, "text/html", "UTF-8", null);
} catch (Throwable t) {
Log.e("ERROR", t.toString() );
browser.loadData("<html><body>" + t.toString() + "</body></html>",
"text/html",
"UTF-8");
}//updateForecast
}
// //////////////////////////////////////////////////////////////////////////
void buildForecasts(String raw) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(raw)));
NodeList times = doc.getElementsByTagName("start-valid-time");
for (int i = 0; i < times.getLength(); i++) {
Element time = (Element) times.item(i);
Forecast forecast = new Forecast();
forecasts.add(forecast);
forecast.setTime(time.getFirstChild().getNodeValue());
}
NodeList temps = doc.getElementsByTagName("value");
for (int i = 0; i < temps.getLength(); i++) {
Element temp = (Element) temps.item(i);
Forecast forecast = forecasts.get(i);
forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
}
NodeList icons = doc.getElementsByTagName("icon-link");
for (int i = 0; i < icons.getLength(); i++) {
Element icon = (Element) icons.item(i);
Forecast forecast = forecasts.get(i);
forecast.setIcon(icon.getFirstChild().getNodeValue());
}
}
String generatePage() {
StringBuffer bufResult = new StringBuffer("<html><body><table>");
bufResult.append("<tr><th width=\"50%\">Time</th>"
+ "<th>Temperature</th><th>Forecast</th></tr>");
for (Forecast forecast : forecasts) {
bufResult.append("<tr><td align=\"center\">");
bufResult.append(forecast.getTime());
bufResult.append("</td><td align=\"center\">");
bufResult.append(forecast.getTemp());
bufResult.append("</td><td><img src=\"");
bufResult.append(forecast.getIcon());
bufResult.append("\"></td></tr>");
}
bufResult.append("</table></body></html>");
return (bufResult.toString());
}
2
/////////////////////////////////////////////////////////////////
class Forecast {
String time = "";
Integer temp = null;
String iconUrl = "";
String getTime() {
return (time);
}
void setTime(String time) {
this.time = time.substring(0, 16).replace('T', ' ');
}
Integer getTemp() {
return (temp);
}
void setTemp(Integer temp) {
this.temp = temp;
}
String getIcon() {
return (iconUrl);
}
void setIcon(String iconUrl) {
this.iconUrl = iconUrl;
}
}
}//Forecast
Layout
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webkit"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Manifest – Permission(s)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.internet">
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="4" />
<application>
<activity android:name=".WeatherDemo" android:label="WeatherDemo">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3
WEB SERVICES
REQUEST (HttpGet sent to website using IExplorer)
http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?&lat=
41.479700&lon=-81.678500&product=time-series&begin=2004-01-01T00:00:00&end=2011-1203T00:00:00&temp=temp&icons=icons
RESPONSE
<?xml version="1.0" ?>
- <dwml version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.
xsd">
- <head>
- <product srsName="WGS 1984" concise-name="time-series" operational-mode="official">
<title>NOAA's National Weather Service Forecast Data</title>
<field>meteorological</field>
<category>forecast</category>
<creation-date refresh-frequency="PT1H">2011-02-17T16:28:30Z</creation-date>
</product>
+ <source>
</head>
- <data>
- <location>
<location-key>point1</location-key>
<point latitude="41.48" longitude="-81.68" />
</location>
<moreWeatherInformation applicablelocation="point1">http://forecast.weather.gov/MapClick.php?textField1=41.48&textField2=81.68</moreWeatherInformation>
- <time-layout time-coordinate="local" summarization="none">
<layout-key>k-p3h-n35-1</layout-key>
<start-valid-time>2011-02-17T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-17T16:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-17T19:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-17T22:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T04:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T10:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T16:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T19:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-18T22:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T04:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T10:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T16:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-19T19:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-20T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-20T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-20T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-20T19:00:00-05:00</start-valid-time>
4
<start-valid-time>2011-02-21T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-21T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-21T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-21T19:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-22T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-22T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-22T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-22T19:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-23T01:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-23T07:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-23T13:00:00-05:00</start-valid-time>
<start-valid-time>2011-02-23T19:00:00-05:00</start-valid-time>
</time-layout>
- <parameters applicable-location="point1">
- <temperature type="hourly" units="Fahrenheit" time-layout="k-p3h-n35-1">
<name>Temperature</name>
<value>57</value>
<value>57</value>
<value>52</value>
<value>49</value>
<value>48</value>
<value>46</value>
<value>46</value>
<value>49</value>
<value>53</value>
<value>51</value>
<value>41</value>
<value>36</value>
<value>33</value>
<value>31</value>
<value>29</value>
<value>33</value>
<value>37</value>
<value>37</value>
<value>33</value>
<value>29</value>
<value>28</value>
<value>38</value>
<value>33</value>
<value>29</value>
<value>27</value>
<value>33</value>
<value>29</value>
<value>26</value>
<value>25</value>
<value>34</value>
<value>29</value>
<value>24</value>
<value>23</value>
<value>35</value>
<value>33</value>
</temperature>
- <conditions-icon type="forecast-NWS" time-layout="k-p3h-n35-1">
<name>Conditions Icons</name>
<icon-link>http://forecast.weather.gov/images/wtf/bkn.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/ovc.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/novc.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/novc.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nra40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nra40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nra40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/shra40.jpg</icon-link>
5
<icon-link>http://forecast.weather.gov/images/wtf/bkn.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nfew.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nbkn.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/novc.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/shra40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nrasn40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsn60.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsn60.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sn40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsn40.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsn30.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsn30.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sn20.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nbkn.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/sct.jpg</icon-link>
<icon-link>http://forecast.weather.gov/images/wtf/nsct.jpg</icon-link>
</conditions-icon>
</parameters>
</data>
</dwml>
6
MONEY EXCHANGE (RSS agent)
// Using RSS to find the current rate of exchange for USD
// data taken from http://themoneyconverter.com/USD/rss.xml
// example uses background thread for slow internet process
// and foreground thread for GUI management
// --------------------------------------------------------package cis493.testa;
import
import
import
import
import
import
import
java.io.IOException;
java.io.InputStream;
java.net.HttpURLConnection;
java.net.MalformedURLException;
java.net.URL;
java.net.URLConnection;
java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import
import
import
import
import
org.w3c.dom.DOMException;
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.NodeList;
org.xml.sax.SAXException;
import
import
import
import
import
import
import
import
import
import
import
android.app.ListActivity;
android.content.Context;
android.os.Bundle;
android.os.Handler;
android.util.Log;
android.view.View;
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.ProgressBar;
android.widget.TextView;
android.widget.Toast;
public class USD_Exchange extends ListActivity {
ArrayList<SingleNewsItem> newsList = new ArrayList<SingleNewsItem>();
ArrayAdapter<String> aa;
String exchangeDate = "";
ProgressBar myBar1;
Handler myHandler = new Handler();
Context myMainContext;
TextView myMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show circular progress bar while other things are done
myBar1 = (ProgressBar)findViewById(R.id.myProgress1);
myMsg = (TextView) findViewById(R.id.myMsg);
myMainContext = getApplicationContext();
}//onCreate
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try {
String text = "Position: " + position
+ "\n"
+ newsList.get(position).getDescription();
Toast.makeText(this, text, 1).show();
// do something useful with the data
} catch (Exception e) {
Log.e("<<EXCHANGE ERROR>>", e.getMessage());
}
}
@Override
7
protected void onStart() {
super.onStart();
// create background thread were the busy work will be done
Thread myThread1 = new Thread(backgroundTask, "getRssMoneyData" );
myThread1.start();
}
/////////////////////////////////////////////////////////////////////
//this is the "Runnable" object that executes the background thread
private Runnable backgroundTask = new Runnable () {
@Override
public void run() {
//busy work goes here...
try {
getRssPopulateListView();
myHandler.post(foregroundTask);
}
catch (Exception e) {
e.printStackTrace();
}
}//run
};//backgroundTask
// //////////////////////////////////////////////////////////////////
// this is the foreground "Runnable" object responsible for the GUI
// when RSS process is it shows list and removes circular progress bar
private Runnable foregroundTask = new Runnable() {
@Override
public void run() {
try {
myMsg.setText(exchangeDate);
myBar1.setVisibility(View.INVISIBLE);
// use your own (small font) layout to show a single row
int layoutID = R.layout.my_simple_list_item_1;
// show on a ListView news held in ArrayList just assembled
ArrayAdapter<SingleNewsItem> aaNews =
new ArrayAdapter<SingleNewsItem>(
myMainContext,
layoutID,
newsList);
setListAdapter(aaNews);
}
catch (Exception e) {
e.printStackTrace();
}
}
}; //foregroundTask
/////////////////////////////////////////////////////////////////////
public void getRssPopulateListView(){
try {
// go to web site, pickup RSS feed
URL url = new URL("http://themoneyconverter.com/USD/rss.xml");
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// create an parse tree for the XML input stream
Document dom = db.parse(in);
// this will be a single node in the tree
Element docEle = dom.getDocumentElement();
// extract individual exchange values
// such as: (1 US Dollar = xx other currency)
NodeList nl = docEle.getElementsByTagName("item");
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
dissectNode(nl, i);
8
}// for
}// if
}// if
} catch (MalformedURLException e) {
Log.v("1-disecting", e.getMessage());
} catch (IOException e) {
Log.v("2-disecting", e.getMessage());
} catch (ParserConfigurationException e) {
Log.v("3-disecting", e.getMessage());
} catch (SAXException e) {
Log.v("4-disecting", e.getMessage());
}
}
/////////////////////////////////////////////////////////////////
public void
//
//
//
//
//
try {
dissectNode(NodeList nl, int i){
examine input collection (NodeList) holding items,
get from each news item the first child of elements:
title, description, pubData, link. Put those pieces
together into a SingleNewsItem object and add it to
the ArrayList called: newsList
Element entry = (Element) nl.item(i);
Element title = (Element) entry.getElementsByTagName(
"title").item(0);
Element description = (Element) entry.getElementsByTagName(
"description").item(0);
Element pubDate = (Element) entry.getElementsByTagName(
"pubDate").item(0);
Element link = (Element) entry.getElementsByTagName(
"link").item(0);
String titleValue = title.getFirstChild().getNodeValue();
String descriptionValue =description.getFirstChild().getNodeValue();
String dateValue = pubDate.getFirstChild().getNodeValue();
String linkValue = link.getFirstChild().getNodeValue();
// combine title & description for a simple ListView
titleValue += "\n " + descriptionValue;
if (exchangeDate.length()==0){
exchangeDate = dateValue;
}
// assemble 'singleItems' add each to the collection
SingleNewsItem singleItem = new SingleNewsItem(
dateValue,titleValue,
descriptionValue, linkValue);
newsList.add(singleItem);
} catch (DOMException e) {
e.printStackTrace();
}
}//dissectNode
}//class
MAIN LAYOUT
<?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"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff006666"
>
<ProgressBar
android:id="@+id/myProgress1"
android:layout_width="wrap_content"
9
android:layout_height="wrap_content"
android:layout_margin="5px"
style="?android:attr/android:progressBarStyleSmall"/>
<TextView
android:id="@+id/myMsg"
android:text="Please wait ..."
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
my_simple_list_line_1.xml (small font)
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:textSize="14sp"
android:minHeight="40sp"
/>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.testa"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".USD_Exchange"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Fragment of [ response ] RSS XML file received by client
http://themoneyconverter.com/USD/rss.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="../css/rss.css" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Exchange Rates For US Dollar</title>
<link>http://themoneyconverter.com/USD/Default.aspx</link>
<description>The latest currency exchange rates for US Dollar</description>
<lastBuildDate>Thu, 17 Feb 2011 21:15:39 GMT</lastBuildDate>
<language>en-us</language>
10
<copyright>Copyright: (C) The Money Converter, see http://themoneyconverter.com/ </copyright>
<docs>http://themoneyconverter.com/RSSFeeds.aspx</docs>
<ttl>15</ttl><image>
<title>Exchange Rates For US Dollar</title>
<url>http://themoneyconverter.com/images/artwork/TheMoneyConveD01aR02aP01ZL_sml.jpg</url>
<link>http://themoneyconverter.com/USD/Default.aspx</link></image>
<item>
<title>AED/USD</title><link>http://themoneyconverter.com/USD/AED.aspx</link>
<guid>e4600198-9686-4cfa-b20d-fb8a31919420</guid>
<pubDate>Thu, 17 Feb 2011 21:15:39 GMT</pubDate>
<description>1 US Dollar = 3.6725 United Arab Emirates Dirham</description>
<category>Middle East</category>
</item>
<item>
<title>ARS/USD</title><link>http://themoneyconverter.com/USD/ARS.aspx</link>
<guid>7d01193a-a366-4cde-ac37-caec09d6faae</guid>
<pubDate>Thu, 17 Feb 2011 21:15:39 GMT</pubDate>
<description>1 US Dollar = 4.02397 Argentine Peso</description>
<category>South America</category>
</item>
11
CONSUMING WEB SERVICES PLACED IN AN APACAHE TOMCAT 7.0 SERVER
This example assumes you have installed the Apache Tomcat 7.0 Server in your computer
(Download from: http://tomcat.apache.org/download-70.cgi). The server comes with a set of samples located in
the folder C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\examples\servlets
(assuming you installed on Windows, using Program Files directory).
In this sample the webservices are implemented in Java Servlets. One of them is the requestParamentersExample.
{[execute.gif]}{[return.gif]}
Source
import
import
import
import
Code for Request Parameter Example
java.io.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
public class RequestParamExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request Parameters Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Request Parameters Example</h3>");
out.println("Parameters in this request:<br>");
if (firstName != null || lastName != null) {
out.println("First Name:");
out.println(" = " + HTMLFilter.filter(firstName) + "<br>");
out.println("Last Name:");
out.println(" = " + HTMLFilter.filter(lastName));
} else {
out.println("No Parameters, Please enter some");
}
out.println("<P>");
out.print("<form action=\"");
out.print("RequestParamExample\" ");
out.println("method=POST>");
out.println("First Name:");
out.println("<input type=text size=20 name=firstname>");
out.println("<br>");
out.println("Last Name:");
out.println("<input type=text size=20 name=lastname>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
In the example we need to supply first and last name. The request object is sent to the service, the arguments are
extracted and echoed back to the user in a response object. The response is a well formed HTML document. In our
Android application we drop the response into a WebView for displaying.
For the sake of the example assume the web server’s IP address is 192.169.0.183. When using the Android
emulator we cannot use the url http://localhost:8080 neither http://127.0.0.1:8080 (the connection will be
refused because of collisions with the emulator). Insteac you will have to provide a ‘real’ IP url.
12
Layout
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webkit"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</WebView>
Manifest needs Internet permission
<uses-permission android:name="android.permission.INTERNET" />
Code
// Consuming a web-service residing in an local Apache Tomcat server
// WebService is a sample that comes with the installation package.
// The example asks for user's first & last name.
// The response is a valid HTML file that echoes the input values.
// -------------------------------------------------------------------package ucr.netdemo1;
import . . .
public class Main extends Activity {
TextView textView;
WebView browser;
public enum RequestMethod {
GET, POST
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this,
"Warning!\nThis code needs your Apache server's current IP.", 1).show();
browser = (WebView) findViewById(R.id.webkit);
useMethod1();
// useMethod2();
// try this method first
// try this method next
}// onCreate
//
//
//
//
//
=============================================================================
VERSION 1.
You assemble the URL. Separate arguments with a '$' sign. Arguments are
pair of name=value elements (eg. firstname=maria)
Based on: http://www.agilemedicine.com/medBlog/?tag=defaulthttpclient
public void useMethod1() {
// url consists of: link2WebServRepository?servletName&argument(s)
String url = "http://192.168.0.183:8080/examples/servlets/servlet/"
+ "RequestParamExample?firstname=Maria1&lastname=Macarena1";
try {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpGet methodGet = new HttpGet(uri);
HttpResponse response = client.execute(methodGet);
InputStream isResponseData = response.getEntity().getContent();
String strResponseData = generateString(isResponseData);
// responseData is an HTML document. Just dump it into the Android's
// WebView
browser.loadDataWithBaseURL(null, strResponseData, "text/html",
"UTF-8", null);
} catch (Exception e) {
Log.e("<<ERROR_VERSION2>>", e.getMessage());
}
}// useMethod2
13
// ---------------------------------------------------------------------------public String generateString(InputStream stream) {
// convert input byte stream into a character stream
InputStreamReader reader = new InputStreamReader(stream);
// place character stream in a buffer
BufferedReader buffer = new BufferedReader(reader);
StringBuilder stringbuilder = new StringBuilder();
// extract lines from buffer, put then in string builder
try {
String currentLine = "";
while ((currentLine = buffer.readLine()) != null) {
stringbuilder.append(currentLine + "\n");
}
} catch (IOException e) {
Log.e("<<ERROR2_1>>", e.getMessage());
}
try {
stream.close();
} catch (IOException e) {
Log.e("<<ERROR2_2>>", e.getMessage());
}
return stringbuilder.toString();
}
// ======================================================================
private void useMethod2() {
// VERSION 2 - Assembling data and headers. Based on code from:
// http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
// http://www.giantflyingsaucer.com/blog/?p=1462
// ----------------------------------------------------------------------// In this example we installed Apache Tomcat 7.0 Server in a Windows
// box. We must use the assigned IP (localhost or 127.0.0.1 doesn't work)
// be careful, this value changes from session to session!!!
// Example asks for first & last name. The response echoes the input
// values.
RestClient rclient = new RestClient(
"http://192.168.0.183:8080/examples/servlets/servlet/RequestParamExample");
rclient.AddParam("firstname", "Maria2");
rclient.AddParam("lastname", "Macarena2");
// Header parameters are optional
rclient.AddHeader("Host", "192.168.0.183:8080");
rclient.AddHeader("Content-Type", "application/x-www-form-urlencoded");
rclient.AddHeader("Accept-Language", "en-US,en;q=0.8");
try {
rclient.Execute(RequestMethod.GET);
} catch (Exception e) {
textView.setText(e.getMessage());
}
// response is an HTML document. Just dump it into the Android's WebView
String response = rclient.getResponse();
browser.loadDataWithBaseURL(null, response, "text/html", "UTF-8", null);
}
// //////////////////////////////////////////////////////////////////////
public class RestClient {
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
14
public int getResponseCode() {
return responseCode;
}
public RestClient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception {
switch (method) {
case GET: {
// add parameters
String combinedParams = "";
if (!params.isEmpty()) {
combinedParams += "?";
for (NameValuePair p : params) {
String paramString = p.getName() + "="
+ URLEncoder.encode(p.getValue(), "UTF-8");
if (combinedParams.length() > 1) {
combinedParams += "&" + paramString;
} else {
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST: {
HttpPost request = new HttpPost(url);
// add headers
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url) {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);
HttpClient hclient = new DefaultHttpClient(httpParams);
// HttpClient hclient = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = hclient.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
15
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
hclient.getConnectionManager().shutdown();
Toast.makeText(getApplicationContext(), e.getMessage(), 1)
.show();
} catch (IOException e) {
hclient.getConnectionManager().shutdown();
Toast.makeText(getApplicationContext(), e.getMessage(), 1)
.show();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e("<<ERROR>>", e.getMessage());
} finally {
try {
is.close();
} catch (IOException e) {
Log.e("<<ERROR>>", e.getMessage());
}
}
return sb.toString();
}
}// RestClient
}// Main
16
Examples of WebServices for an IIS Server
ServiceDb.asmx
' simple web-services implemented in VisualBasic for an IIS server
' V. Matos - Feb 2011
' --------------------------------------------------------------------------------------------Imports System.Web.Services
Imports System.Data.Odbc
<System.Web.Services.WebService(Namespace:="http://tempuri.org/WebServiceDB/ServiceDB")> _
Public Class ServiceDB
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
...
#End Region
' WEB SERVICE EXAMPLE
' To test this web service, ensure that the .asmx file
' is the start page and press F5.
'---------------------------------------------------------<WebMethod()> _
Public Function MySum(ByVal A As Double, ByVal B As Double) As Double
'adding two positive numbers
If A < 0 Then A = 0
If B < 0 Then B = 0
Return (A + B)
End Function
<WebMethod()> _
Public Function MyDiff(ByVal A As Double, ByVal B As Double) As Double
'subtracting two positive numbers
If A < 0 Then A = 0
If B < 0 Then B = 0
If (A - B) < 0 Then
Return 0
Else
Return (A - B)
End If
End Function
<WebMethod()> _
Public Function MyEcho(ByVal inputMsg As String) As String
' echoe input value
Return (inputMsg + " ... " + inputMsg + " ... " + inputMsg)
End Function
<WebMethod()> _
Public Function GetProjects() As DataSet
'get PROJECT table from Oracle database
Dim oraCnn As New OdbcConnection
Dim DS As New DataSet
'using a local DSN defined in the local machine
Dim oraCsuPersonStr As String = "DSN=myOracleSANCHO;UID=CSUPERSON;PWD=EUCLID"
oraCnn.ConnectionString = oraCsuPersonStr
If oraCnn.State = ConnectionState.Closed Then
oraCnn.Open()
End If
Dim oraDA As New OdbcDataAdapter("select * from PROJECT", oraCnn)
oraDA.Fill(DS, "PROJECT")
oraCnn.Close()
Return DS
End Function
<WebMethod()> _
Public Function GetProjectsLocatedIn(ByVal theCity As String) As DataSet
'get PROJECTs located in a given city (try Cleveland, Houston,...)
Dim mySQL As String
Dim oraCnn As New OdbcConnection
'using a local DSN defined in the local machine
Dim oraCsuPersonStr As String = "DSN=myOracleSANCHO;UID=CSUPERSON;PWD=EUCLID"
Dim DS As New DataSet
oraCnn.ConnectionString = oraCsuPersonStr
If oraCnn.State = ConnectionState.Closed Then
oraCnn.Open()
End If
17
Try
mySQL = "select * from PROJECT where Plocation = '" + theCity + "'"
Dim oraDA As New OdbcDataAdapter(mySQL, oraCnn)
oraDA.Fill(DS, "PROJECT")
Catch ex As Exception
'nada to return
End Try
oraCnn.Close()
Return DS
End Function
End Class
Web.config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections><system.web>
<!-- DYNAMIC DEBUG COMPILATION
Set compilation debug="true" to insert debugging symbols (.pdb information)
into the compiled page. Because this creates a larger file that executes
more slowly, you should set this value to true only when debugging and to
false at all other times. For more information, refer to the documentation about
debugging ASP.NET files.
-->
<compilation defaultLanguage="vb" debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
<!-- CUSTOM ERROR MESSAGES
Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable.
Add <error> tags for each of the errors you want to handle.
"On" Always display custom (friendly) messages.
"Off" Always display detailed ASP.NET error information.
"RemoteOnly" Display custom (friendly) messages only to users not running
on the local Web server. This setting is recommended for security purposes, so
that you do not display application detail information to remote clients.
-->
<customErrors mode="RemoteOnly"/>
<!-- AUTHENTICATION
This section sets the authentication policies of the application. Possible modes are "Windows",
"Forms", "Passport" and "None"
"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to
its settings for the application. Anonymous access must be disabled in IIS.
"Forms" You provide a custom form (Web page) for users to enter their credentials, and then
you authenticate them in your application. A user credential token is stored in a cookie.
"Passport" Authentication is performed via a centralized authentication service provided
by Microsoft that offers a single logon and core profile services for member sites.
-->
<authentication mode="None"/>
<!-- AUTHORIZATION
This section sets the authorization policies of the application. You can allow or deny access
to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous
(unauthenticated) users.
-->
<authorization>
<allow users="*"/>
<!-- Allow all users -->
<!-- <allow users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
<deny users="[comma separated list of users]"
roles="[comma separated list of roles]"/>
-->
</authorization>
<!-- APPLICATION-LEVEL TRACE LOGGING
Application-level tracing enables trace log output for every page within an application.
Set trace enabled="true" to enable application trace logging. If pageOutput="true", the
trace information will be displayed at the bottom of each page. Otherwise, you can view the
application trace log by browsing the "trace.axd" page from your web application
root.
-->
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
<!-- SESSION STATE SETTINGS
By default ASP.NET uses cookies to identify which requests belong to a particular session.
If cookies are not available, a session can be tracked by adding a session identifier to the URL.
To disable cookies, set sessionState cookieless="true".
-->
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"/>
<!-- GLOBALIZATION
This section sets the globalization settings of the application.
-->
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
<xhtmlConformance mode="Legacy"/>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls></pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD 364E35"/></httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpModules></system.web>
<system.codedom>
<compilers>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/></compiler></compilers></system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/></handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly></assemblyBinding></runtime></configuration>
18
Testing the IIS Services: Screen-shots
Services are exposed at: http://localhost/WebServiceDB/ServiceDB.asmx
Remember to change Web.config to
<authentication mode="None"/> so you do not have to
authenticate the session (bypass the prompt below). You need to: Stop, Refresh, Start IIS (check IIS > Default Web
Site icon > Properties > Directory Security > Edit > tick on allow “Anonymous Access” > Apply > OK ).
19
Invoking service: MyEcho
Response
20
Testing the service: GetProjectsLocatedIn (you enter a city value such as: Houston, Cleveland, …)
<?xml version="1.0" encoding="utf-8" ?>
- <DataSet xmlns="http://tempuri.org/WebServiceDB/ServiceDB">
- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
- <xs:complexType>
- <xs:choice minOccurs="0" maxOccurs="unbounded">
- <xs:element name="PROJECT">
- <xs:complexType>
- <xs:sequence>
<xs:element name="PNAME" type="xs:string" minOccurs="0" />
<xs:element name="PNUMBER" type="xs:decimal" minOccurs="0" />
<xs:element name="PLOCATION" type="xs:string" minOccurs="0" />
<xs:element name="DNUM" type="xs:decimal" minOccurs="0" />
</xs:sequence>
21
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
- <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
- <NewDataSet xmlns="">
- <PROJECT diffgr:id="PROJECT1" msdata:rowOrder="0">
<PNAME>ProductZ</PNAME>
<PNUMBER>3</PNUMBER>
<PLOCATION>Houston</PLOCATION>
<DNUM>5</DNUM>
</PROJECT>
- <PROJECT diffgr:id="PROJECT2" msdata:rowOrder="1">
<PNAME>Reorganization</PNAME>
<PNUMBER>20</PNUMBER>
<PLOCATION>Houston</PLOCATION>
<DNUM>1</DNUM>
</PROJECT>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
22