240 likes | 404 Views
Working with Webservices. Nilanjan Banerjee. University of Arkansas Fayetteville, AR n ilanjan.banerjee@gmail.com. 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
E N D
Working with Webservices Nilanjan Banerjee University of Arkansas Fayetteville, AR nilanjan.banerjee@gmail.com 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 (extracting maps, geocoding, reverse geocoding)
Other advanced webservices? Optical Character Recognition System (OCR) Relay services and Rendezvous Services Speech to Text Service
General architecture for accessing databases Intermediary Script (php, perl etc) Backend database Mobile Phone
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(); • - db.inc.php <? $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"); ?>
Authenticating userinfo (server side) • 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 <?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(); ?>
Adding text to a mysql database • 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 $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();
Retrieving text from a mysql server and sending it back mysql_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);
Code on the phone httpclient = new DefaultHttpClient(); 91 httppost = new HttpPost(php_script); 92 // Add your data 93 nameValuePairs = new ArrayList<NameValuePair>(2); 94 nameValuePairs.add(newBasicNameValuePair("UserEmail", name.trim())); 95 nameValuePairs.add(newBasicNameValuePair("Password", pass.trim())); 96 httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs)); 97 98 // Execute HTTP Post Request 99 response = httpclient.execute(httppost); 100 inputStream = response.getEntity().getContent(); 101 102 data = new byte[256]; 103 104 buffer = new StringBuffer(); 105 intlen = 0; 106 while (-1 != (len = inputStream.read(data)) ) 107 { 108 buffer.append(newString(data, 0, len)); 109 } 110 111 inputStream.close();
Uploading images to a mysql server enter where image is stored and its Characteristics (size etc) database php script store Image in a folder Name of image and attributes Send actual images folder Phone
Schematic for upload of images String (Base64 encoded) String byte binary (Base64 decoded) ByteArray OutputStream image Bitmap Image Server Android
Uploading images to the server <?php $base=$_REQUEST['image']; echo $base;// base64 encoded utf-8 string $binary=base64_decode($base);// binary, utf-8 bytes header('Content-Type: bitmap; charset=utf-8’); $file = fopen('test.jpg', 'wb'); fwrite($file, $binary);fclose($file); echo '<imgsrc=test.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(newBasicNameValuePair("image",image_str)); 34 35 try{ 36 HttpClienthttpclient = new DefaultHttpClient(); 37 HttpPosthttppost = new HttpPost(php_script); 38 httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs)); 39 HttpResponse response = httpclient.execute(httppost); String the_string_response = convertResponseToString(response); }catch(Exceptione){ }
Sending images from the phone (Response) String res = ""; StringBuffer buffer = new StringBuffer(); inputStream = response.getEntity().getContent(); intcontentLength = (int) response.getEntity().getContentLength(); 55 if (contentLength < 0){ 56 } 57 else{ 58 byte[] data = new byte[512]; 59 intlen = 0; 60 try 61 { 62 while (-1 != (len = inputStream.read(data)) ) 63 { 64 buffer.append(newString(data, 0, len)); 65 } 66 } 67 catch (IOExceptione) {} 71 try 72 { 73 inputStream.close(); 74 } 75 catch (IOExceptione) {} res = buffer.toString(); . 83 } 84 return res; 85 }
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“
SMS Sending • Step 3 Import Classes and Interfaces • import 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;
SMS Sending Input from the user (i.e., the phone no, text message and sendSMS is implemented). • Step 4 Write the SMS class public class SMS extends Activity { Button btnSendSMS; EditTexttxtPhoneNo; EditTexttxtMessage; /** 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(); } }); } }
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); SmsManagersms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, pi, null); }
Receiving SMS Step 1
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>
Receiving SMS • Step 3 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.widget.Toast;
Receiving SMS 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 • Step 4 public 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 (inti=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(); } } }