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

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

Jun 23, 2016 pm 01:35 PM

概述

    本节通过一个简单的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['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);?>
Copy after login

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


结尾

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

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

*鲁阳高科工作室

*网       址:www.bigbearking.com

*商务合作QQ:1519190237

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

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


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles