wamp集成环境+eclipse环境开发
php代码如下:
<?php
headler('content-type:text/html;charset=utf-8');
//与mysql建立连接
$con=new mysqli('localhost','root','');
//选择连接的数据库
$con->select_db('test');
$con->charset('utf-8');
//判断是否连接成功
if($mysqli-connect_errro){
die('Connect Error:'.$mysqli->connect_error);
}
}
//接收Android端发来的数据
$username=$_POST['user'];
$password=$_POST['passwd'];
$sql="select * from users";
//执行sql语句,并返回数据
$result=mysqli_query($con,$sql
);
//定义一个数组
$data=array();
//定义一个类,用来保存数据
class users{
public $name;
public $id;
}
while($row=mysqli_fetch_array){
$user=new users();
$user->id=$row['id'];
$user->
name=$row['username'];
$data=$user;
}
//转换成JSON格式数据输出
echo json_encode($data);
android端
建立xml文件,自己简单设计一个登陆界面
在onCreate方法开启一个子线程
MyThread OneThread= new MyThread();
OneThread.start();
public class MyThread extends Thread {
@Override
public void run() {
super.run();
HttpPost httpRequest = new HttpPost(Php_Url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
final String user = username.getText().toString();
final String passwd = password.getText().toString();
params.add(new BasicNameValuePair("user", user));
params.add(new BasicNameValuePair("passwd", passwd));
// params.add(new BasicNameValuePair("latitude", "-15.415121"));
try {
HttpEntity httpEntity = new UrlEncodedFormEntity(params,
"utf-8");// 设置编码格式
httpRequest.setEntity(httpEntity); // 根据URL的地址,向目标发送参数以及编码
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);// 对服务器做出响应,这是一个响应对象
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// SC_OK==200,代表响应成功
String result = EntityUtils.toString(httpResponse
.getEntity());
// tv.setText(result);
Log.i(TAG, "result = " + result);
try {
JSONObject jsonObject = new JSONObject(result);
retCode = jsonObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
if (retCode == 1) {
Message msg = Message.obtain();
msg.what = 1;
msg.obj = result;
handler.sendMessage(msg);
} else {
// Toast.makeText(MainActivity.this,"用户名或密码错误!",Toast.LENGTH_SHORT).show();
}
} else {
// tv.setText("request error");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//建立一个handler对象,用来更新UI界面
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (1 == msg.what) {
Toast.makeText(MainActivity.this, "欢迎您。。。登陆成功!",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this,"用户名或密码错误!",Toast.LENGTH_SHORT).show();
}
};
};