Android client to communicate with the server-side PHP (b) --- JSON interaction

Outline

    This section provides a simple demo program introduced a simple Android client submits an order to the server via PHP JSON, PHP server post-processing orders, returns the results to the Android client through JSON. Now normally, PHP server to process orders in process, the need to interact with the MySQL database, here for simplicity, temporarily save MySQL.

Communication format

First, the need to set communication format between client and server, the following table


Android client

    The client and server communicate using JSON data format, while using the HTTP communication protocol interaction, using POST method to submit the results. Also note that the process of communicating with other WEB server needs to open up a thread for data acquisition, which can prevent After acquiring the program fails, the main thread can run, I began to experiment when there is no notice of this, because of a communications failure caused the program to stop running.

    At the same time due to the need of network communication, we need to add the following statement permissions in AndroidManifest.xml


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

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

    Figure procedure is relatively simple structure, only a MainActivity.java.


    Operating results for the


MainActivity.java 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, "启动程序 ");
		BtnRequest = (Button)findViewById(R.id.BtnRequest);
		//绑定事件源和监听器对象
		BtnRequest.setOnClickListener(new ButtonRequestListener());
	}
	
	//内部类,实现OnClickListener接口
    //作为第二个按钮的监听器类
    class ButtonRequestListener implements OnClickListener
    {
        public void onClick(View v)
        {        	
        	Log.i(TAG, "按钮按下 ");
        	StartRequestFromPHP();
        	Log.i(TAG, "执行完毕 ");
        }

    }
    
    private void StartRequestFromPHP() 
    { 
    	//新建线程
    	new Thread(){
    		public void run(){

    			try { 
    				SendRequest();  				
    			} catch (Exception e) { 
    				e.printStackTrace(); 
    			} 
    		}
    	}.start();
    }
    
    private  void SendRequest(){
    	//通过HttpClient类与WEB服务器交互
    	HttpClient httpClient = new DefaultHttpClient();
    	//定义与服务器交互的地址
        String ServerUrl = "http://www.bigbearking.com/study/guestRequest.php";
        //设置读取超时,注意CONNECTION_TIMEOUT和SO_TIMEOUT的区别
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        //设置读取超时
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        //POST方式
        HttpPost httpRequst = new HttpPost(ServerUrl);        
        //准备传输的数据
        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{
        	//发送请求
            httpRequst.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //得到响应
            HttpResponse response = httpClient.execute(httpRequst);            
            //返回值如果为200的话则证明成功的得到了数据
            if(response.getStatusLine().getStatusCode() == 200)
            {
                      StringBuilder builder = new StringBuilder();                      
                      //将得到的数据进行解析
                      BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                      //readLine()阻塞读取
                      for(String s =buffer.readLine(); s!= null; s = buffer.readLine())
                      {
                    	  builder.append(s);                               
                      }
                      
                      System.out.println(builder.toString());
                      //得到Json对象
                      JSONObject jsonObject   = new JSONObject(builder.toString());
                      
                      //通过得到键值对的方式得到值
                     int CmdId = jsonObject.getInt("CMDID");
                     String SResult = jsonObject.getString("SResult");
                     String SUserName = jsonObject.getString("SUserName");
                     int SResultPara = jsonObject.getInt("SResultPara");

                     Log.i(TAG, "读取到数据 ");
                     Log.i(TAG, "RequestResult:"+SResult);
                     Log.i(TAG, "UserName:"+SUserName);
                     //在线程中判断是否得到成功从服务器得到数据
                                         
            }
            else{
            	Log.e(TAG, "连接超时 ");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            Log.e(TAG, "请求错误 ");
            Log.e(TAG, e.getMessage());
        }

    	return ;
    }

}


Web server source code

guestRequest.php content:

<?php
	
	//获取客户端发来的请求信息
	$CmdId = $_POST['CMDID'];
	$UserName = $_POST['CUserName'];
	$OrderName = $_POST['COrderName'];
	
	
	if($UserName != 'lygk')
	{
		$result = 'Fail';
		$resultpara = 2;
		//将数据存储到数据中
		$arr = array(			
			'CMDID' => $CmdId,
			'SUserName' => $UserName,
			'SResult'=>$result,
			'SResultPara' =>$resultpara
			);
				//将数组转成json格式进行传递
		$strr = json_encode($arr);
	}
	else
	{
		$result = 'Success';
		$resultpara = 1;
		//将数据存储到数据中
		$arr = array(			
			'CMDID' => $CmdId,
			'SUserName' => $UserName,
			'SResult'=>$result,
			'SResultPara' =>$resultpara
			);
				//将数组转成json格式进行传递
		$strr = json_encode($arr);
	}

	echo($strr);

?>

    Run the software, click on "Send Request" button, you can see operating information from LogCat, WEB server has successfully processed the request response sent by the Android client.


end

    This chapter describes the interaction Android client and the WEB server, attached to source more, we found less about principles, one of which the details, please review Jun own taste. Android client source code, click here to download

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

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

* Lu Yang Tech Studios

* Website: www.bigbearking.com

* Business cooperation QQ: 1519190237

Scope of service: construction sites, desktop software development, Android \ IOS development, film and television post-image processing, PCB design

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


Published 143 original articles · won praise 161 · Views 1.21 million +

Guess you like

Origin blog.csdn.net/mybelief321/article/details/45423143