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>
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);?>
运行软件,点击“发送请求”按钮后,从LogCat可以看到运行信息,WEB服务器已经成功响应处理了Android客户端发送的请求。
结尾
本章主要介绍了Android客户端与WEB服务端的交互,贴的源码比较多,发现讲的原理少,其中个中细节,请君自行品味查阅。Android客户端源码,点此下载
/*****************************************************************************************************
*鲁阳高科工作室
*网 址:www.bigbearking.com
*商务合作QQ:1519190237
*业 务 范 围:网站建设、桌面软件开发、Android\IOS开发、图像影视后期处理、PCB设计
****************************************************************************************************/

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
