Rumah >pembangunan bahagian belakang >tutorial php >Android 客户端与PHP服务器的简单交互&&登录注册实例
服务器采用本地的apache服务器,所有的php文件都写在D:\AppServ\www目录下。。之前也一直在写请求的代码,一直没有成功,原因是请求的url有问题。。请求的url一定要跟自己服务器的端口号一致。如何改变端口号,参看 :http://jingyan.baidu.com/article/a65957f4fe8ec424e67f9bff.html
设置好自己的端口号之后,还需要注意一下请求的url格式:
该php文件在本地保存的地址是这样的 :D:\AppServ\www\get_data.json
在android客户端 中:url-------------- "http://10.0.2.2:8080/get_data.json"
在网页 :HTTP http://127.0.0.1:8080/get_data.json/
这里一定要弄正确。。然后启动apache
一,客户端准备
需要加入网络权限,由于网络请求时耗时操作,所以把请求的内容都写在了一个继承与thread的子类中。
1.MainActivity.java
package com.example.log_user;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.os.Build;public class MainActivity extends ActionBarActivity { EditText user_name; EditText pass_word; Button login; Button zhuce; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); user_name=(EditText) findViewById(R.id.editText1); pass_word=(EditText) findViewById(R.id.editText2); login=(Button) findViewById(R.id.button1); zhuce=(Button) findViewById(R.id.button2); login.setOnClickListener(new OnClickListener(){ String url="http://10.0.2.2:8080/config.inc.php"; @Override public void onClick(View arg0) { String user=user_name.getText().toString(); String pass=pass_word.getText().toString(); // TODO Auto-generated method stub new LoginThread(user,pass,url).start(); Log.d("MAIN","-------------------->MAINSUCCESS"); } }); zhuce.setOnClickListener(new OnClickListener(){ String url="http://10.0.2.2:8080/test_signup.php"; @Override public void onClick(View arg0) { // TODO Auto-generated method stub String user=user_name.getText().toString(); String pass=pass_word.getText().toString(); new signup(user,pass,url).start(); Log.d("Main","------------------->signupsuccess"); } }); }}
2.LoginThread.java登录
简单说一下这个类,之前也因为没有意识到需要新建子线程而犯了很多错误。继承于thread,把需要执行的操作放在run方法里。gotoLogin方法用来判断输入用户名和密码是否与服务器所连数据库里面的字段匹配。这里用了httpClient来处理post请求,需要将传递的数据放在这个数组里。
ArrayList<NameValuePair> params在执行了post请求之后
HttpResponse respose=client.execute(post);会返回一个httpresponse,将这个对象转为string之后其实就是请求的php url页面所echo 出来的字符串。
String content=EntityUtils.toString(respose.getEntity());
package com.example.log_user;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.content.res.Resources.Theme;import android.util.Log;import android.widget.Toast;public class LoginThread extends Thread { String username; String password; String Url; @Override public void run() { // TODO Auto-generated method stub super.run(); Log.d("run","-------------------->MAINSUCCESS"); boolean isLoginSuccess=gotoLogin(username,password,Url); if(isLoginSuccess){ Log.d("Log","--------------------->登录成功"); } else { Log.d("Log","--------------------->登录失败"); } } public LoginThread(String user,String pass,String url){ this.username=user; this.password=pass; this.Url=url; } public boolean gotoLogin(String user,String pass,String url){ boolean issuccess=false; String result; //发送post请求 HttpClient client=new DefaultHttpClient(); HttpPost post = new HttpPost(url); //Post运作传送变数必须用NameValuePair[]阵列储存 ArrayList<NameValuePair> params=new ArrayList3.signup.java注册页面 :原理与登录类似(); params.add(new BasicNameValuePair("name",user)); params.add(new BasicNameValuePair("password",pass)); try { post.setEntity(new UrlEncodedFormEntity(params)); try { HttpResponse respose=client.execute(post); if(respose.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ String content=EntityUtils.toString(respose.getEntity()); Log.d("post","--------------------->success"); Log.d("post",content+""); if(content.equals("logsuccess")){ issuccess=true; } } else { Log.d("post","--------------------->failes"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return issuccess; } }
package com.example.log_user;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import android.util.Log;public class signup extends Thread { private String username; private String password; private String url; @Override public void run() { // TODO Auto-generated method stub super.run(); boolean issuccess=doPOSThttp(username,password,url); if(issuccess){ Log.d("sign","-------------->signsuccess"); } else { Log.d("sign","-------------->signfailue"); } } public signup(String user,String password,String url){ this.username=user; this.password=password; this.url=url; } public boolean doPOSThttp(String username,String password,String url){ boolean issuccess=false; HttpClient client=new DefaultHttpClient(); HttpPost post =new HttpPost(url); ArrayList<NameValuePair> param=new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("name",username)); param.add(new BasicNameValuePair("password",password)); try { post.setEntity(new UrlEncodedFormEntity(param)); try { HttpResponse response=client.execute(post); if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ String cont=EntityUtils.toString(response.getEntity()); Log.d("post","------------>"+cont); if(cont.equals("signsuccess")) { issuccess=false; } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return issuccess; } }
二。服务器准备
1,config.inc.php 这个是与客户端的登录请求对应。通过$_POST方法取到传递的数据,在于数据库里面的数据匹配一下,匹配成功,则echo 一个标示字符串,用来使客户端用response取到该字符串进行判断。
<?$db_host=localhost;$db_user="root";$db_pass="123456789";$db_name="stu";$table_name="student";/* mysql_query('set names utf8'); */if($con=mysql_connect($db_host,$db_user,$db_pass)){ }else{ echo "连接失败";}if(mysql_select_db(web_01)){}else{ echo "选择数据库失败";}$username=$_POST['name'];$sql="select * from my_user where name='$username'";$query=mysql_query($sql);if($row=mysql_fetch_array($query)){ if($_POST['password']==$row['password']) echo "logsuccess";}mysql_close($con);?>
2.test_signup.php 这个与客户端的注册请求对应。
<? $db_host=localhost;$db_user="root";$db_pass="123456789";$db_name="stu";$table_name="student";/* mysql_query('set names utf8'); */if($con=mysql_connect($db_host,$db_user,$db_pass)){ }else{ echo "连接失败";}if(mysql_select_db(web_01)){}else{ echo "选择数据库失败";}$username=$_POST['name'];$pass=$_POST['password'];if(mysql_query('insert into my_user(name,password) values($username,$pass)')){ echo "signsuccess";}mysql_close($con);?>