php android 源码,Android与PHP服务器数据连接源码

这篇博客展示了如何使用Android客户端通过HTTP POST请求与PHP服务器进行交互,实现用户注册功能。客户端源码详细说明了如何设置请求参数、发送数据到服务器并解析返回的JSON响应。同时,PHP服务器端的代码展示了接收和处理注册信息的过程,包括数据验证和存入数据库。
摘要由CSDN通过智能技术生成

Android客户端的源码:

/*** * *@author 马琳的笔记本 *@date 2015 9-17 * 测试第一个对应user1.php */

public class MainActivity extends Activity {

private static final String TAG="测试语句显示:";

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 BtnRequestListener());

}

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

return super.onOptionsItemSelected(item);

}

class BtnRequestListener implements OnClickListener{

public void onClick(View newview) {

Log.i(TAG, "连接按钮开始....");

StartRequestFromPHP();

Log.i(TAG, "连接PHP特别成功,执行完毕....");

}

private void StartRequestFromPHP(){

//新建线程;

new Thread(){

public void run(){

try{

SendRequest();

}catch(Exception ex){

ex.printStackTrace();

}

}

}.start();

}

private void SendRequest(){

//通过HttpClient类与WEB服务器交互;

HttpClient httpClient=new DefaultHttpClient();

//定义与服务器交互的地址;

String ServerUrl="http://www.recordyears.com/userlogin.php";

//设置读取超时,注意connection_timeout和so_timeout的区别

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);

//设置读取超时

httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

//设置POST传递数据方式

HttpPost httpRequest=new HttpPost(ServerUrl);

//准备传输数据

List param=new ArrayList();

param.add(new BasicNameValuePair("username", "android与php的测试"));

param.add(new BasicNameValuePair("password", "android"));

param.add(new BasicNameValuePair("email", "email@123456.com"));

param.add(new BasicNameValuePair("sex", "male"));

param.add(new BasicNameValuePair("major", "网络工程"));

param.add(new BasicNameValuePair("description", "计算机学院网络121级"));

try{

//发送请求

httpRequest.setEntity(new UrlEncodedFormEntity(param,HTTP.UTF_8)) ;

//得到响应;

HttpResponse response=httpClient.execute(httpRequest);

//返回值如果是200的话那么证明成功的得到数据

if(response.getStatusLine().getStatusCode()==200){

StringBuilder strbuilder=new StringBuilder();

//得到额数据输入缓冲流中解析一下;

BufferedReader buffer=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

//变成strbuilder字符串;

for(String str=buffer.readLine();str!=null;str=buffer.readLine()){

strbuilder.append(str);

}

System.out.println("获取的值是:"+strbuilder.toString());

//用json解析;

JSONObject jsonObject=new JSONObject(strbuilder.toString());

//通多得到键值对的方式获取收到的数据;

int userId=jsonObject.getInt("userId");

String username=jsonObject.getString("username");

String course=jsonObject.getString("course");

int counter=jsonObject.getInt("counter");

Log.i(TAG, "读取到数据...");

Log.i(TAG, "counter:"+counter);

Log.i(TAG, "userId:"+userId);

//显示线程是否得到成功从服务器得到数据;

}else{

Log.i(TAG, "连接超时!");

}

}catch(Exception ex){

ex.printStackTrace();

Log.i(TAG, "连接过程出现错误...");

Log.i(TAG, ex.getMessage());

}

return;

}

}

Android的AndroidMenifest.xml文件:源码

package="com.recordyears.main"

android:versionCode="1"

android:versionName="1.0" >

android:minSdkVersion="8"

android:targetSdkVersion="15" />

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@android:style/Theme.Black.NoTitleBar" >

android:name=".MainActivity"

android:label="@string/app_name" >

android:name="com.recordyears.main.AndroidtoServer"

android:label="@string/app_name" >

Android的layout.xml的源码:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.recordyears.main.MainActivity" >

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/BtnRequest"

android:text="我们去连接"

android:background="#F00"

/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text=" "

android:id="@+id/text"

/>

然后php服务器文件:

/* * 写于2015年9月16号,主要实现一个课堂签到功能 * 本PHP页面主要是接受注册的功能用户,并把它们写入到数据库中; * 连接数据库的代码块在mysql_con.php; * */

header("Content-type: text/html; charset=utf-8");

session_start();

$username= str_replace(" ","",$_POST["username"]);

$emailaddr= str_replace(" ","",$_POST["email"]);

$classid=str_replace(" ","",$_POST["classid"]);

$major=str_replace(" ","",$_POST["major"]);

$description =str_replace(" ","",$_POST["description"]);

echo "用户名:$username 邮件: $emailaddr 学生学号:$classid 主修专业:$major 个人描述:$description ";

$conn=mysql_open();

$code=md5($_POST[password].ALL_PS);

// $sql="insert into reuser(id,username,classid,password,email) values(1,2,'$username','$code','$emailaddr')";

$query=mysql_query($sql);

mysql_close($conn);

if($query){

//echo "注册成功";

$_SESSION["Username"]=$username;

$_SESSION["Passed"]=True;

echo "";

//header("Location:index.php");

}

?>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值