HTTP Post在android中不使用PHP
我正在学习android,并试图编写一些代码,使用PHP脚本和WAMP服务器验证用户名和密码。我的PHP脚本中不断出现未定义的索引错误。据我所知,这意味着我的PHP脚本无法从URL访问数据。这是相关代码。感谢您的帮助HTTP Post在android中不使用PHP,php,android,http,Php,Android,Http,我正在学习android,并试图编写一些代码,使用PHP脚本和WAMP服务器验证用户名和密码。我的PHP脚本中不断出现未定义的索引错误。据我所知,这意味着我的PHP脚本无法从URL访问数据。这是相关代码。感谢您的帮助 //build url data to be sent to server ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); n
//build url data to be sent to server
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
//生成要发送到服务器的url数据
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,username));
添加(新的BasicNameValuePair(“密码”,password));
字符串结果=”;
InputStream=null;
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://10.0.2.2/PasswordCheck.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
Log.e(“连接”,“http连接中的错误”+e.toString());
}
这是我的PHP脚本
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
$username = $_POST["username"];
$suppliedPassword = $_POST["password"];
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
在我看来,您的Android代码似乎没有发布“用户名”和“密码”字段,这就解释了为什么PHP脚本找不到它们
在代码中,newarraylist()代码>,通过查看此代码,arrayList的长度可能会丢失:看起来它应该是新的arrayList(2)代码>,您应该尝试一下,看看是否解决了问题。结果表明,这是一个简单的拼写错误。我在循环中的“password”一词中使用了小写字母“p”,而不是大写字母。奇怪的是,它导致了错误。您可以在PHP中尝试json_decode()函数:
尝试在您的服务器上创建一个文件,并将android请求的内容放入简单的文本文件中,您将获得数组输出。在那个档案里
在服务器的.php文件中编写以下代码:
<?php
$data=file_put_content(collect.txt, $_POST);
// if you got to know object or array name from txt file use it.
$array=json_decode($data, true) // for array output.
print_r($array);
?>
若你们不想从文件中读取数据,你们可以直接使用json对象中的数组名
<?php
$array=json_decode($data) // remove true for use as an object output.
print_r($array);
?>
一旦你得到了你的数组,给新的变量赋值,并对它们做任何你想做的事情。根据您的要求更新数据库或任何内容。请根据需要增长ArrayList,这样就不会出现问题。不过还是谢谢你。