您的位置:首页 > 移动开发 > Android开发

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

2015-09-18 10:43 477 查看
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<BasicNameValuePair> param=new ArrayList<BasicNameValuePair>();

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文件:源码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.recordyears.main"
android:versionCode="1"
android:versionName="1.0" >

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

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<!-- 最起码的要有网络服务权限 -->

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.recordyears.main.AndroidtoServer"
android:label="@string/app_name" >
</activity>

</application>

</manifest>
Android的layout.xml的源码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/BtnRequest"
android:text="我们去连接"
android:background="#F00"
/>

<TextView

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" "
android:id="@+id/text"

/>

</RelativeLayout>
然后php服务器文件:
<?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 "<script>window.location.href='index.php'</script>";

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

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android与PH