Home > Backend Development > PHP Tutorial > Android客户端与PHP服务端通讯(二)

Android客户端与PHP服务端通讯(二)

WBOY
Release: 2016-06-13 12:18:53
Original
1002 people have browsed it

Android客户端与PHP服务端通信(二)

概述

    本节通过一个简单的demo程序简单的介绍Android客户端通过JSON向PHP服务端提交订单,PHP服务端处理订单后,通过JSON返回结果给Android客户端。正常来讲,PHP服务端在处理订单过程中,需要与MySQL数据库交互,这里为了简单起见,暂时省掉MySQL。

通信格式

首先,需要定下客户端与服务端之间通信格式,如下表


Android客户端

    客户端与服务端采用JSON数据格式通信,同时采用HTTP通信协议交互,采用POST方式提交结果。同时还要注意一点,与WEB服务器通信的过程需要另开辟一个线程进行数据的获取,这样可以防止获取程序失败之后,主线程还可以运行,我开始实验的时候没有注意到这一点,由于通信失败造成了程序停止运行。

    同时由于需要网络通信,所以需要在AndroidManifest.xml中添加如下权限语句



    程序的构造图比较简单,只有一个MainActivity.java。


    运行效果为


MainActivity.java内容如下

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 ;    }}</basicnamevaluepair></basicnamevaluepair>
Copy after login


Web服务端源码

guestRequest.php内容:

<?php //获取客户端发来的请求信息	$CmdId = $_POST[&#39;CMDID&#39;];	$UserName = $_POST[&#39;CUserName&#39;];	$OrderName = $_POST[&#39;COrderName&#39;];			if($UserName != &#39;lygk&#39;)	{		$result = &#39;Fail&#39;;		$resultpara = 2;		//将数据存储到数据中		$arr = array(						&#39;CMDID&#39; => $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);?>
Copy after login

    运行软件,点击“发送请求”按钮后,从LogCat可以看到运行信息,WEB服务器已经成功响应处理了Android客户端发送的请求。


结尾

    本章主要介绍了Android客户端与WEB服务端的交互,贴的源码比较多,发现讲的原理少,其中个中细节,请君自行品味查阅。Android客户端源码,点此下载

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

*原创文章,转载请注明网址:http://blog.csdn.net/mybelief321/article/details/45423143

*鲁阳高科工作室

*网       址:www.bigbearking.com

*商务合作QQ:1519190237

*业 务 范 围:网站建设、桌面软件开发、Android\IOS开发、图像影视后期处理、PCB设计

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template