Android front-end how PHP background interaction (Basic article)
The simple interaction between the Android client and the Php+mysql+apache built server enables the login function. The implementation of the principle is that the Android client sends a request to the server login username password, the server received these, connected to the database query, if the user name and password match correctly, the output string returned to the client.
Android and PHP interactive Android and Java interaction are the same, Android write interface through HTTP request PHP to receive the request after the server do processing return value Android received and then show it
again The principle is actually interacting with HTML and PHP.
Server side: First in MySQL to build a testlogin database, which has a users table, recorded ID, username and password.
Create a new PHP project in the PHP virtual directory, creating conn.php and login.php files. Just learn a little php writing is not good. Conn.php is connected to the MySQL database. The code is as follows: <?php $dbhost = "localhost:3306"; $dbuser = "root"; My user name $dbpass = ""; my password. $dbname = "Testlogin"; My MySQL library name $CN = mysql_connect ($dbhost, $dbuser, $dbpass) or Die ("Connect error"); @mysql_select_db ($dbname) or Die ("DB error"); mysql_query ("Set names ' UTF-8 '"); ? >login.php Code: <?php Include ("conn.php");//Connect database $username =str_replace ("", "", $_post[' name ']);//receive username from client; $sql = "SELECT * from Users where name= ' $username '"; $query =mysql_query ($sql); $rs = Mysql_fetch_array ($query); if (Is_array ($rs)) { if ($_post[' pwd ']== $rs [' password ']) { echo "Login Succeed"; }else{ echo "Error"; } } ?> Copy Code
PHP code is poorly written, the server is set up. Android Client:
Here's the main code: Class Loginhandler implements Runnable { @Override public void Run () { TODO auto-generated Method Stub Get username and password; UserName = User_name.gettext (). toString (). Trim (); Password = Pass_word.gettext (). toString (). Trim (); Connect to the address of the server, I am listening to the 8080 port String connecturl= "http://192.168.1.100:8080/text0/com.light.text/login.php/"; Fill in Username password and connection address Boolean isloginsucceed = Gotologin (UserName, Password,connecturl); Determines whether the return value is true, and jumps to the home page if it is. if (isloginsucceed) { Intent Intent = new Intent (); Intent.setclass (Getapplicationcontext (), homeactivity.class); StartActivity (Intent); Prodialog.dismiss (); }else{ Prodialog.dismiss (); Toast.maketext (clientactivity.this, "Login Error", Toast.length_long). Show (); SYSTEM.OUT.PRINTLN ("Login error"); } } }//login method, incoming user password and connection address Private Boolean Gotologin (String userName, String password,string connecturl) { String result = null; Used to obtain the returned string; Boolean isloginsucceed = false; Test System.out.println ("Username:" +username); System.out.println ("Password:" +password); Send POST request HttpPost HttpRequest = new HttpPost (Connecturl); Post operation transfer variables must be stored with namevaluepair[] Array List params = new ArrayList (); Params.add (New Basicnamevaluepair ("name", UserName)); Params.add (New Basicnamevaluepair ("pwd", password)); try{ Issuing HTTP Requests Httprequest.setentity (New Urlencodedformentity (params,http). Utf_8)); Get HTTP response HttpResponse httpresponse=new defaulthttpclient (). Execute (HttpRequest); If the status code is 200, the request succeeds and the return data is taken if (Httpresponse.getstatusline (). Getstatuscode () ==200) { Remove a string Result=entityutils.tostring (Httpresponse.getentity ()); Ystem.out.println ("result=" +result); } }catch (Exception e) { E.printstacktrace (); } To determine if the returned data is the output of a successful login in PHP if (result.equals ("Login Succeed")) { Isloginsucceed = true; } return isloginsucceed; Copy Code
Successful login will jump to the home page:
Code so much, the simplest way to login, in fact, there are many to implement, you need to save the user name and password and login after successful or unsuccessful feedback.
|
To be honest, the PHP server is to do logic and data processing, then output in a fixed format, Android uses the HTTP protocol or SOAP and other protocols to get the corresponding data.
The front-end does not need to know how to achieve a specific background, just know what I want, and then encapsulate these things backstage to you He (return).
Android client and server data interaction process
The process of making a portal site:
First of all, the Web designer only to do web design, that is, painting the site in the browser to display the appearance, and then by the front-end staff to write HTML+CSS+JS to achieve the dynamic effect of the site, such as navigation bar Drop-down display, and then Ajax local information updates, and then through the background program such as jsp,php. NET and other languages, the information in the database and the front page of the combination, so that a station is so built.
And the Android client, also has UI designer, UI front-end, program composition, the same program side, the recent HTML5+CSS3 hot open, many companies also need HTML5+CSS3 to carry out the development of Android programs. Whining, robbing me of my job. Although said elder brother also understands Html+css. Hey, this explanation, perhaps we do not know, in fact, wood is necessary to find out the site of the construction process, here is just for everyone to popularize knowledge, there is no need to find out.
Basics: We need to know that the HTTP protocol is based on the TCP protocol, and the TCP protocol is a connected, reliable transmission protocol, if it is lost, it will be retransmission. So then, there will be no loss of data.
The HTTP protocol has three methods, Get,post,head methods, but with only get and Post methods, the Get method puts the request parameter in the request header, so the requested parameter is visible in the URL, and the Post method puts the request parameter in the data section. So in the URL is not visible, post is relatively confidential, so in the submission of important information, the use of HttpPost methods to achieve.
and in B/S mode, the browser, s on behalf of the server, in the browser and server communication, because the B/s will not always remain connected, so will add a cookie mechanism to identify the object of operation.
The user browses the Web page by the following actions: When a user clicks on a connection or a button, the browser sends a request to the server, then the server receives the request, resolves to what the user requested, then finds the relevant resources, returns the data to the browser, parses the data by the browser, The user is then displayed to see the page that the user needs to see.
So, Android and B/S mode is similar, in fact, is to send a request, receive data, and then parse the data, showing the process on the phone, there is no big difference, who let me use the Internet, using the TCP/IP protocol, yes.
To be understood: all operations are the process of requesting data from the server.
First, we need to familiarize ourselves with Android's HttpGet and HttpPost requests. Of these, Apache has provided two classes, called: HttpGet and HttpPost two classes. Two classes are used differently and do not interpret the paste code: 1. Use HttpGet to request Baidu's homepage: Using the HttpGet method, Baidu's homepage is introduced into HttpGet hettpget = new HttpGet ("http://www.baidu.com/"); Use the default HttpClient HttpClient HC = new Defaulthttpclient (); try { Executes the HttpGet method and gets the response returned HttpResponse response = Hc.execute (Hettpget); If the response code is 200, the success is obtained, otherwise an error occurs if (Response.getstatusline (). Getstatuscode () = = 200) { S is getting the HTML code String s = entityutils.tostring (Response.getentity ()); System.out.println (s); } catch (Clientprotocolexception e) { E.printstacktrace (); catch (IOException E) {E.printstacktrace (); } |
This is to Baidu server sent a httpget request, the request is Baidu's search home, the server returned to all is HTML code, but the browser has the function of parsing HTML, the HTML code into the displayed page, so, printed out are HTML code.
Send a request using HttpPost HttpPost HttpPost = new HttpPost (URL); Use Namevaluepaira to save incoming parameters in the request list<namevaluepair> paramas = new arraylist<namevaluepair> (); Paramas.add (New Basicnamevaluepair ("A", "a")); try { HttpResponse HttpResponse; Put Namevaluepair into the HttpPost request body Httppost.setentity (New Urlencodedformentity (Paramas, HTTP. Utf_8)); Execute HttpPost Request HttpResponse = new Defaulthttpclient (). Execute (httppost); If the response code is 200, the success is obtained, otherwise an error occurs if (Httpresponse.getstatusline (). Getstatuscode () = = 200) { String s = entityutils.tostring (HttpResponse . GetEntity ()); catch (Unsupportedencodingexception e) { TODO auto-generated Catch block &nb |