Don't say anything, directly on the code. If you can not understand the following and I leave a message.
First look at the service side: the use of PHP language, deployed in the Sina SAE server (with the database)
Put all the PHP files in the same directory:
1.db.php encapsulated classes for connecting to a database
<?php class db{static private $_instance;
static private $_connectsource;
Because it is connected to the Sina SAE server, the following parameters do not take effect.
/*private $_dbconfig=array (' Host ' => ' 127.0.0.1 ', ' user ' => ' root ', ' password ' => '), ' Database ' => ' value '); /Private Function _construct () {} static public function getinstance () {//If there are no instances, is created, and then returns the instance that has been created if (!
Self::$_instance instanceof Self)) {self::$_instance =new self ();
return self::$_instance; Public Function Connect () {if (!self::$_connectsource) {Self::$_connectsource=mysql_connect ( Sae_mysql_host_m. ': '.
Sae_mysql_port,sae_mysql_user,sae_mysql_pass); Self::$_connectsource = @mysql_connect ($this->_dbconfig[' host '), $this->_dbconfig[' user ', $this->_
dbconfig[' password ']); if (!self::$_connectsource) {//If the database connection is not successful/throw an exception, catch it through a try catch when the Connnect () function is invokedObtained throw new Exception (' MySQL connect error '. mysql_error);
Die (' MySQL connect error '. mysql_error);
} mysql_select_db (Sae_mysql_db,self::$_connectsource);
mysql_select_db ($this->_dbconfig[' database '), Self::$_connectsource);
mysql_query ("Set names UTF8", Self::$_connectsource);
return self::$_connectsource; }
}
2.response.php used to encapsulate communication data (JSON or XML)
<?php class Response {const JSON = "JSON"; /** * Output communication data in an integrated manner * @param integer $code Status code * @param string $message message * @param array $data data * @param string $t
ype Data Type * return String */public static function show ($code, $message = ', $data = Array (), $type = Self::json) {
if (!is_numeric ($code)) {return '; } $type = isset ($_get[' format '])?
$_get[' format ']: Self::json;
$result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $data,);
if ($type = = ' json ') {Self::json ($code, $message, $data);
Exit
} elseif ($type = = ' array ') {var_dump ($result);
} elseif ($type = = ' xml ') {Self::xmlencode ($code, $message, $data);
Exit else {//TODO}}/** * Output communication data in JSON * @param integer $code Status code * @param string $message message * @param Array $data Data * return String */public static function json ($code, $message = ', $data = Array ()) {if (!is_num
Eric ($code)) {return '; } $result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $data);
echo Json_encode ($result);
Exit /** * Output Communication data by XML * @param integer $code Status code * @param string $message message * @param array $data data * return Stri
NG */public static function Xmlencode ($code, $message, $data = Array ()) {if (!is_numeric ($code)) {return ';
$result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $data,);
Header ("Content-type:text/xml");
$xml = "<?xml version= ' 1.0 ' encoding= ' UTF-8 '" >\n ";
$xml. = "<root>\n";
$xml. = Self::xmltoencode ($result);
$xml. = "</root>";
Echo $xml;
The public static function Xmltoencode ($data) {$xml = $attr = "";
foreach ($data as $key => $value) {if (Is_numeric ($key)) {$attr = "id= ' {$key} '";
$key = "Item";
} $xml. = "<{$key} {$attr}>"; $xml. = Is_array ($value)?
Self::xmltoencode ($value): $value;
$xml. = "</{$key}>\n"; return $xml; }
}
3.checklogin.php is provided to the client to allow the client to use a GET request to pass in the USERNAME,PASSWD authentication login
<?php
//This is App Authentication login interface
//access mode http://****.com/bee/checklogin.php
if ($_get[' format ']== ' xml ') {
Header ("Content-type:text/xml");}
Require_once ('./response.php ');//Introducing Data Encapsulation Class
require_once ('./db.php ');//Introducing Database Class
$username =$_get[' username '] ;
$passwd =$_get[' passwd '];
$sql = "SELECT * from user where ' username ' = ' $username ' and ' passwd ' = ' $passwd '";
try{
$connect =db::getinstance ()->connect ();
} catch (Exception $e) {
response::show (403, ' Database connection failed ');
}
$result =mysql_query ($sql, $connect);
$videos =array ();
MYSQL_FETCH_ASSOC () field name key is value to facilitate client resolution. Each row is fetched, distinguished from mysql_fetch_array () while
($video =mysql_fetch_assoc ($result)) {
$videos []= $video;
}
In this way, the data obtained from the database is saved to $videos[], and then the interface data is converted to an
if ($videos) {
response::show (200, ' Home data acquisition success ', $videos);
This generates JSON data by default, and if XML data is required, Http://...com/list.php?format=xml
}else{
response::show (400, ' Home data acquisition failed ', $videos);
}
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------
Here the service-side code is complete, accepting the client's HHTP GET request, querying the database, verifying the username, and the password is correct. Encapsulate the results into JSON or XML, and output in the browser. For the client to read.
Here are some of the Android client code:
The layout file is not displayed, which is two TextView and two edittext, and a button
Directly on the Mainactivity.java
Package Com.example.bee;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Org.json.JSONArray;
Import org.json.JSONException;
Import Org.json.JSONObject;
Import android.app.Activity;
Import android.content.Intent;
Import android.content.SharedPreferences;
Import Android.content.SharedPreferences.Editor;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
public class Login extends activity {/** * interface for login * * String result= "", user,passwd;
Handler MyHandler;
EditText Userview,passwdview;
Button Login,register;
Thread T;
Sharedpreferences sp;
int code;
String Realname; @Override protected void OnCreate (Bundle SavedinStancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.login);
userview= (EditText) Findviewbyid (R.id.login_edt_user);
passwdview= (EditText) Findviewbyid (R.ID.LOGIN_EDT_PASSWD);
Login= (Button) Findviewbyid (R.id.btn_login);
Register= (Button) Findviewbyid (r.id.btn_register);
Sp=getsharedpreferences ("Login", mode_private);
String getname=sp.getstring ("username", null);
if (getname==null) {toast.maketext (login.this, SP NULL, 0). Show ();
}else{Toast.maketext (login.this, "SP have", 0). Show ();
Userview.settext (sp.getstring ("username", null));
Passwdview.settext (sp.getstring ("passwd", null)); //Login button click event Login.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View V) {//TODO auto-generated method Stub t=new Thread (New Runnable () {@Override Publ
IC void Run () {//TODO auto-generated method stub try {user=userview.gettext (). toString ();
Passwd=passwdview.gettext (). toString ();
URL url=new url ("http://luo.sinaapp.com/e/checklogin.php?username=" +user+ "&passwd=" +passwd);
HttpURLConnection urlconnection= (httpurlconnection) url.openconnection ();
InputStreamReader isr=new InputStreamReader (Urlconnection.getinputstream ());
BufferedReader br=new BufferedReader (ISR);
Result=br.readline ();
Parse the obtained JSON data to try {jsonobject object=new jsonobject (result);
Code=object.getint ("code");
Jsonarray ja= Object.getjsonarray ("data");
String data=ja.getstring (0);
Jsonobject secondobject=new jsonobject (data);
Realname=secondobject.getstring ("Realname");
catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace ();
Message M1=myhandler.obtainmessage (); if (code==400)//Login failed {M1.whaT=1;
Myhandler.sendmessage (M1);
}else if (code==200) {//login successful m1.what=2;
Myhandler.sendmessage (M1);
}else{//Other cases: Networking failure, server anomalies, such as m1.what=3;
Myhandler.sendmessage (M1);
The catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
}
}
});
T.start ();
}
});
Register Click event/*register.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {
TODO auto-generated Method Stub Intent i=new Intent (login.this,registeractivity.class);
StartActivity (i);
}); */Myhandler=new Handler () {@Override public void Handlemessage (msg) {
TODO auto-generated Method Stub super.handlemessage (msg); if (msg.what==1) {Toast.maketext (logiN.this, "Incorrect username or password", 0). Show ();
else if (msg.what==2) {Toast.maketext (Login.this, "Welcome:" +realname, 0). Show ();
* Login successfully write the data to the local save, so that the next automatic amount landing * * sp=getsharedpreferences ("login", mode_private);
Editor Editor=sp.edit ();
Editor.putstring ("username", user);
Editor.putstring ("passwd", passwd);
Editor.putstring ("Realname", realname);
Editor.commit ();
Intent i = new Intent (login.this, Mainactivity.class);
StartActivity (i);
Finish ();
else {toast.maketext (login.this, "network connection Failed", 0). Show ();
}
}
}; }
}
If you do not know the sharedpreference above, please come here to see:
http://blog.csdn.net/davidluo001/article/details/42290369
If you have any other questions please leave a message and answer as soon as possible.