Communication between the Android client and the PHP server (2) --- JSON interaction, android --- json

Source: Internet
Author: User

Communication between the Android client and the PHP server (2) --- JSON interaction, android --- json

Overview

This section uses a simple demo program to briefly introduce the Android client to submit an order to the PHP server through JSON. After the PHP server processes the order, it returns the result to the Android client through JSON. Normally, the PHP server needs to interact with the MySQL database during order processing. For the sake of simplicity, MySQL is temporarily saved.

Communication format

First, you need to set the communication format between the client and the server, as shown in the following table.


Android Client

The client communicates with the server in JSON format, interacts with the server over HTTP, and submits results using POST. At the same time, it should be noted that the process of communicating with the WEB server requires another thread to obtain data, which can prevent the main thread from running after the acquiring program fails, I didn't notice this when I started the experiment, and the program stopped due to communication failure.

In addition, because network communication is required, you must add the following permission statement to AndroidManifest. xml:


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

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

The structure diagram of the program is relatively simple, with only one MainActivity. java.


Running effect:


The content of MainActivity. java 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; I Mport 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, "Startup Program "); BtnRequest = (Button) findViewById (R. id. btnRequest); // bind the event source and listener object BtnRequest. setOnClickListener (new ButtonRequestListener ();} // internal class, implementing the OnClickListener interface // class ButtonRequestListener implements OnClickListener {public void onClick (View v) {Log. I (TAG, "button pressed"); StartRequestFromPHP (); Log. I (TAG, "execution completed") ;}} private void StartRequestFromPHP () {// new Thread () {public void run () {t Ry {SendRequest ();} catch (Exception e) {e. printStackTrace ();}}}. start ();} private void SendRequest () {// interaction with the WEB server through the HttpClient class HttpClient httpClient = new DefaultHttpClient (); // define the address String ServerUrl = "http://www.bigbearking.com/study/guestRequest.php"; // set the read timeout, pay attention to the CONNECTION_TIMEOUT and SO_TIMEOUT differences httpClient. getParams (). setParameter (CoreConnectionPNames. CONNECTION_TIMEOUT, 5000 );// Set the read timeout. getParams (). setParameter (CoreConnectionPNames. SO_TIMEOUT, 5000); // POST method HttpPost httpRequst = new HttpPost (ServerUrl); // List of data to be transmitted <BasicNameValuePair> params = new ArrayList <BasicNameValuePair> (); params. add (new BasicNameValuePair ("Upload ID", "1"); params. add (new BasicNameValuePair ("CUserName", "lygk"); params. add (new BasicNameValuePair ("COrderName", "Apple"); params. add (new BasicNameValuePair ("COrderNum", "2"); try {// send the request httpRequst. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // get the response HttpResponse response = httpClient.exe cute (httpRequst); // if the returned value is 200, the data if (response. getStatusLine (). getStatusCode () = 200) {StringBuilder builder = new StringBuilder (); // parse the obtained data BufferedReader buffer = new BufferedReader (new InputStreamReader (response. getEnt Ity (). getContent (); // readLine () blocks read for (String s = buffer. readLine (); s! = Null; s = buffer. readLine () {builder. append (s);} System. out. println (builder. toString (); // obtain the Json object JSONObject jsonObject = new JSONObject (builder. toString (); // you can obtain the value int jsonid = jsonObject by getting the key-value pair. getInt ("Upload ID"); String SResult = jsonObject. getString ("SResult"); String SUserName = jsonObject. getString ("SUserName"); int SResultPara = jsonObject. getInt ("SResultPara"); Log. I (TAG, "read data"); Log. I (TAG, "RequestResult:" + SResult); Log. I (TAG, "UserName:" + SUserName); // determines whether data is successfully obtained from the server in the thread} else {Log. e (TAG, "connection timeout") ;}} catch (Exception e) {e. printStackTrace (); Log. e (TAG, "request error"); Log. e (TAG, e. getMessage () ;}return ;}}


Web Server Source Code

GuestRequest. php content:

<? Php // obtain the request information sent from the client $ response id = $ _ POST ['response id']; $ UserName = $ _ POST ['cusername']; $ OrderName = $ _ POST ['cordername']; if ($ UserName! = 'Lygk ') {$ result = 'fail'; $ resultpara = 2; // store data to data $ arr = array ('regionid' => $ regionid, 'susername' => $ UserName, 'sresult' => $ result, 'sresultpara' => $ resultpara ); // convert the array to json format and pass $ strr = json_encode ($ arr);} else {$ result = 'success '; $ resultpara = 1; // store data to data $ arr = array ('regionid' => $ regionid, 'susername' => $ UserName, 'sresult' => $ result, 'sresultpara' => $ resultpara); // convert the array to json format and pass $ strr = json_encode ($ arr ); } Echo ($ strr);?>

Run the software and click "Send request". You can see the running information from LogCat. The WEB server has successfully responded to the request sent by the Android client.


End

This chapter mainly introduces the interaction between the Android client and the WEB server. The source code of the post is relatively large, and the principle of the post is found to be few. For details, please read it on your own. Android client source code,Click here to download

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

* Original article, reproduced please note the URL: http://blog.csdn.net/mybelief321/article/details/45423143

* Luyang Gaoke Studio

* Address: www.bigbearking.com

* QQ For Business Cooperation: 1519190237

* Business model: website construction, desktop software development, Android/IOS development, image post-processing, and PCB design

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


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.