working with webservices
DESCRIPTION
Working with Webservices. Nilanjan Banerjee. University of Arkansas Fayetteville, AR n [email protected]. Mobile Systems Programming. Some of the simple web based services you would use!. Writing data to a database. Querying data from a database. Map queries - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/1.jpg)
1
Working with Webservices
Nilanjan Banerjee
Mobile Systems Programming
University of ArkansasFayetteville, AR
![Page 2: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/2.jpg)
Some of the simple web based services you would use!
Writing data to a database
Querying data from a database
Map queries (extracting maps, geocoding, reverse geocoding)
![Page 3: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/3.jpg)
Other advanced webservices?
Optical Character Recognition System (OCR)
Relay services and Rendezvous Services
Speech to Text Service
![Page 4: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/4.jpg)
General architecture for accessing databases
Mobile Phone
Intermediary Script (php, perl etc)
Backend database
![Page 5: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/5.jpg)
Sending simple text data from a Mobile phone (Server side)– Adding userinfo --- username and password
$firstname = $_REQUEST["firstname"];$lastname = $_REQUEST["lastname"];$username = $_REQUEST["username"];$fpassword = $_REQUEST["fpassword"];
require_once('db.inc.php');
$insertquery="INSERT INTO table_name (first_name, last_name, user_name, fpassword) VALUES ('$firstname', '$lastname', '$username', '$fpassword’)";
$result = mysql_query($insertquery);mysql_close();
<?$user=”XXX";$password=”YYY";$database="weedidapp";$host="mpss.csce.uark.edu";mysql_connect($host,$user,$password);@mysql_select_db($database) or die( "Unable to select database");?>
- db.inc.php
![Page 6: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/6.jpg)
Authenticating userinfo (server side)
<?php
foreach ($_GET as $key => $value) { eval("\$" . $key . " = \"" . $value . "\";");}
$username = $_REQUEST["username"];$fpassword = $_REQUEST["fpassword"];require_once('db.inc.php');$query="SELECT * from table where user_name='$username' AND fpassword='$fpassword'";$result = mysql_query($query);if($result && mysql_numrows($result)>0) echo "y”;else echo "n”;mysql_close();?>
– Check that the username password is present in the database– Note that this is all in plaintext. Ideally you would create a MD5
hash of the password and store the hash
![Page 7: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/7.jpg)
Adding text to a mysql database
$latitude = $_REQUEST[”latitude"];$longitude = $_REQUEST[”longitude"];
require_once('db.inc.php');
$insertquery="INSERT INTO table_name (latitude, longitude) VALUES (’$latitude', '$longitude’)";
$result = mysql_query($insertquery);mysql_close();
– Send the data encoded in the url• For e.g., http://www.csce.uark.edu/~nilanb/insertdb.php?latitude=“-
31.5”;longitude=“-94.6”– The url is parsed by the php script and a hashtable with <key,
value> pairs are extraced• _REQUEST[“latitude”] = -31.5• _REQUEST[“longitude”] = -94.6
![Page 8: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/8.jpg)
Retrieving text from a mysql server and sending it backmysql_select_db("locationgame",$con);$list = mysql_list_tables("locationgame");$i = 0;$idarray = array();$latarray = array();$longarray = array();$count = 0;while($i < mysql_num_rows($list)){ $tb_names[$i] = mysql_tablename($list,$i); $sql = "SELECT * FROM $tb_names[$i] order by Date desc limit 1"; $result = mysql_query($sql, $con); $num = mysql_numrows($result); $j = 0; while($j < $num) { $fielddate=mysql_result($result,$j,"Date"); $fieldlatitude = mysql_result($result, $j, "Latitude"); $fieldlongitude = mysql_result($result, $j, "Longitude"); $phpdate = strtotime($fielddate); $dist = distance($fieldlatitude, $fieldlongitude, $latitude, $longitude); $idarray[] = $tb_names[$i]; $latarray[] = $fieldlatitude; $longarray[] = $fieldlongitude; $count ++; $j++; } $i++;}for ($i = 0; $i < $count; $i++){print "$idarray[$i] ”; print "$latarray[$i] ”; print "$longarray[$i] ”; print "\n”;}mysql_close($con);
![Page 9: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/9.jpg)
Code on the phone
httpclient = new DefaultHttpClient();91 httppost = new HttpPost(php_script);92 // Add your data93 nameValuePairs = new ArrayList<NameValuePair>(2);94 nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));95 nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));96 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));97 98 // Execute HTTP Post Request99 response = httpclient.execute(httppost);100 inputStream = response.getEntity().getContent();101 102 data = new byte[256];103 104 buffer = new StringBuffer();105 int len = 0;106 while (-1 != (len = inputStream.read(data)) )107 {108 buffer.append(new String(data, 0, len));109 }110 111 inputStream.close();
![Page 10: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/10.jpg)
Uploading images to a mysql server
php script
Phone
database
folderName of image and attributes
enter where image is stored and itsCharacteristics (size etc)
Send actual images
storeImage in a folder
![Page 11: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/11.jpg)
Schematic for upload of images
Image
Bitmap
ByteArrayOutputStream
byte
String (Base64 encoded) String
binary (Base64 decoded)
image
Android Server
![Page 12: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/12.jpg)
Uploading images to the server
<?php$base=$_REQUEST['image'];echo $base;// base64 encoded utf-8 string$binary=base64_decode($base);// binary, utf-8 bytesheader('Content-Type: bitmap; charset=utf-8’);$file = fopen('test.jpg', 'wb');fwrite($file, $binary);fclose($file);echo '<img src=test.jpg>';?>
![Page 13: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/13.jpg)
Sending images from the phone
29 byte [] byte_arr = stream.toByteArray();30 String image_str = Base64.encodeBytes(byte_arr);31 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();32 33 nameValuePairs.add(new BasicNameValuePair("image",image_str));34 35 try{36 HttpClient httpclient = new DefaultHttpClient();37 HttpPost httppost = new HttpPost(php_script);38 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));39 HttpResponse response = httpclient.execute(httppost);40 String the_string_response = convertResponseToString(response);42 }catch(Exception e){ }
![Page 14: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/14.jpg)
Sending images from the phone (Response) String res = "";
StringBuffer buffer = new StringBuffer(); inputStream = response.getEntity().getContent();
53 int contentLength = (int) response.getEntity().getContentLength(); 55 if (contentLength < 0){56 }57 else{58 byte[] data = new byte[512];59 int len = 0;60 try61 {62 while (-1 != (len = inputStream.read(data)) )63 {64 buffer.append(new String(data, 0, len)); 65 }66 }67 catch (IOException e)68 {}71 try72 {73 inputStream.close(); 74 }75 catch (IOException e)76 {}79 res = buffer.toString(); .83 }84 return res;85 }
![Page 15: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/15.jpg)
SMS Sending• STEP 1
– In the AndroidManifest.xml file, add the two permissions - SEND_SMS and RECEIVE_SMS.
• STEP 2– In the main.xml, add Text
view to display "Enter the phone number of recipient“ and "Message"
– EditText with id txtPhoneNo and txtMessage
– Add the button ID "Send SMS“
![Page 16: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/16.jpg)
SMS Sending
• Step 3 Import Classes and Interfacesimport android.app.Activity;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;
![Page 17: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/17.jpg)
SMS Sending
Step 4 Write the SMS class public class SMS extends Activity { Button btnSendSMS; EditText txtPhoneNo; EditText txtMessage; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); txtMessage = (EditText) findViewById(R.id.txtMessage); btnSendSMS.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String phoneNo = txtPhoneNo.getText().toString(); String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0) sendSMS(phoneNo, message); else Toast.makeText(getBaseContext(), "Please enter both phone number and message.", Toast.LENGTH_SHORT).show(); } }); } }
Input from the user (i.e., the phone no, text message and
sendSMS is implemented).
![Page 18: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/18.jpg)
SMS Sending
Step 5◦ To send an SMS message, you use the SmsManager class.
And to instantiate this class call getDefault() static method.
◦ The sendTextMessage() method sends the SMS message with a PendingIntent.
◦ The PendingIntent object is used to identify a target to invoke at a later time.
private void sendSMS(String phoneNumber, String message) { PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMS.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, pi, null);}
![Page 19: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/19.jpg)
SMS Sending
![Page 20: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/20.jpg)
Receiving SMS
• Step 1
![Page 21: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/21.jpg)
Receiving SMS
• Step 2– In the AndroidManifest.xml file add the <receiver> element so
that incoming SMS messages can be intercepted by the SmsReceiver class.
<receiver android:name=".SmsReceiver"> <intent-filter> <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
![Page 22: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/22.jpg)
Receiving SMS
• Step 3import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.telephony.SmsMessage;import android.widget.Toast;
![Page 23: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/23.jpg)
Receiving SMS
Step 4public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null){ //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); str += " :"; str += msgs[i].getMessageBody().toString(); str += "\n"; } //---display the new SMS message--- Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } }}
In the SmsReceiver class, extend the
BroadcastReceiver class and override the
onReceive() method. The message is attached to
the Intent
The messages are stored in a object array PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class
![Page 24: Working with Webservices](https://reader035.vdocuments.us/reader035/viewer/2022062310/56815b99550346895dc9a098/html5/thumbnails/24.jpg)
Receiving SMS