Android client communication with PHP server (ii)

Source: Internet
Author: User

Overview

In this section, a simple demo program simply introduces the Android client to submit an order via JSON to the PHP server, and after the PHP server processes the order, it returns the result to the Android client via JSON. Normally, the PHP server needs to interact with the MySQL database as it processes the order, and for the sake of simplicity, save MySQL for the time being.

Communication Format

First, you need to define the communication format between the client and the server, such as the following table


Android Client

The client and the server use the JSON data format to communicate, and the HTTP communication protocol is used to submit the result using the Post method. It is also important to note that the process of communicating with the Web server requires a separate thread for data acquisition, which prevents the master thread from running after the failed acquisition, and I did not notice this when I started the experiment because the communication failure caused the program to stop running.

At the same time, because of the need for network communication, you need to add the following permission statements in Androidmanifest.xml


<uses-permission android:name= "Android.permission.INTERNET"/>

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>

The construction diagram of the program is relatively simple, with only one mainactivity.java.


Operation Effect is


Mainactivity.java content is as follows

Package Com.lygk.jsontest;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.util.arraylist;import Java.util.list;import Org.apache.http.httpentity;import Org.apache.http.HttpResponse; Import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.params.coreconnectionpnames;import Org.apache.http.protocol.http;import Org.json.JSONObject; Import Com.example.jsontest.r;import android.app.activity;import android.os.bundle;import Android.os.Handler; Import Android.os.message;import android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import  Android.widget.toast;public class Mainactivity extends Activity {  private static final String tag= "Lygk"; Button btnrequest;protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); LOG.I (TAG, "starter program"); Btnrequest = (Button) Findviewbyid (r.id.btnrequest);//bind event source and Listener object Btnrequest.setonclicklistener (new Buttonrequestlistener ());} Inner class, implement Onclicklistener interface//As listener class for second button Buttonrequestlistener implements Onclicklistener {public V        OID OnClick (View v) {log.i (TAG, "button pressed");        Startrequestfromphp ();        LOG.I (TAG, "execution complete"); }} private void startrequestfromphp () {//New threads New Thread () {public void run () {try {Send      Request ();     } catch (Exception e) {e.printstacktrace ();    }}}.start ();    private void SendRequest () {//HttpClient class interacts with the Web server HttpClient HttpClient = new Defaulthttpclient (); Defines the address that interacts with the server String ServerURL = "Http://www.bigbearking.com/study/guestReqUest.php "; Set the Read timeout, note the difference between connection_timeout and So_timeout Httpclient.getparams (). Setparameter (coreconnectionpnames.connection        _timeout, 5000);        Set read Timeout Httpclient.getparams (). Setparameter (Coreconnectionpnames.so_timeout, 5000);                Post mode HttpPost httprequst = new HttpPost (ServerURL);                        Ready to transmit data list<basicnamevaluepair> params = new arraylist<basicnamevaluepair> ();        Params.add (New Basicnamevaluepair ("CMDID", "1"));        Params.add (New Basicnamevaluepair ("Cusername", "LYGK"));        Params.add (New Basicnamevaluepair ("Cordername", "Apple"));                Params.add (New Basicnamevaluepair ("Cordernum", "2")); try{//Send request httprequst.setentity (new urlencodedformentity (params, HTTP.            Utf_8));                        Get response HttpResponse response = Httpclient.execute (httprequst); The return value, if 200, proves successful if the data is obtained if (Response.getstatusline (). Getstatuscode (= =) {StringBuilder builder = new StringBuilder (); The resulting data is parsed bufferedreader buffer = new BufferedReader (New InputStreamReader (response.get                      Entity (). getcontent ());                      ReadLine () block reads for (String s =buffer.readline (); s!= null; s = buffer.readline ())                                                     {Builder.append (s);                      } System.out.println (Builder.tostring ());                                            Get the JSON object Jsonobject jsonobject = new Jsonobject (builder.tostring ());                     Get the value int CmdId = Jsonobject.getint ("CmdId") by getting the key-value pair.                     String Sresult = jsonobject.getstring ("Sresult");                     String sUserName = jsonobject.getstring ("sUserName"); int SresuLtpara = Jsonobject.getint ("Sresultpara");                     LOG.I (TAG, "read to Data");                     LOG.I (TAG, "Requestresult:" +sresult);                     LOG.I (TAG, "UserName:" +susername); Determine if the data was successfully obtained from the server in the thread} else{log.e (TAG, "Connection timed out            ");            }}catch (Exception e) {e.printstacktrace ();            LOG.E (TAG, "request Error");        LOG.E (TAG, E.getmessage ());    } return; }}


Web service-side source code

guestrequest.php content:

<?php//gets the request information sent by the client $cmdid = $_post[' CmdId '; $UserName = $_post[' Cusername ']; $OrderName = $_post[' Cordername '];if ( $UserName! = ' Lygk ') {$result = ' Fail '; $resultpara = 2;//stores the data in the data $arr = Array (' CMDID ' = = $CmdId, ' susername ' = = $User Name, ' sresult ' = $result, ' sresultpara ' = $resultpara);//Convert the array to JSON format to pass $STRR = Json_encode ($arr);} else{$result = ' Success '; $resultpara = 1;//stores the data in the data $arr = Array (' CMDID ' = $CmdId, ' susername ' = $UserName, ' Sresult ' + $result, ' sresultpara ' = $resultpara);//Convert the array to JSON format to pass $STRR = Json_encode ($arr);} Echo ($STRR);? >

Run the software, click on the "Send Request" button, from Logcat can see the running information, the Web server has successfully responded to processing the Android client sent the request.


End

This chapter mainly introduces the interaction between the Android client and the Web server, the source of the paste is much more, found that the principle of less, including the details, please your own taste check. Android client source, Click here to download

/*****************************************************************************************************

* Original articles, reproduced please specify the website: http://blog.csdn.net/mybelief321/article/details/45423143

* Luyang High Tech Studio

* Website: www.bigbearking.com

* Business Cooperation qq:1519190237

* Business Scope: Website construction, desktop software development, Android\ios development, image and film post-processing, PCB design

****************************************************************************************************/


Android client communication with PHP server (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.