我遇到了一个奇怪的问题,当我收到来自 PHP 页面的响应时,将其存储在 Java 中的字符串变量中并尝试将其与我键入的相同字符串进行比较,它由于某种原因返回 false。
我正在尝试创建一个登录类来验证用户详细信息是否存储在 MySQL 上。
if("User Found".equals(response))
即使响应包含相同的内容,此语句也会返回 false。
这是Java和PHP代码:
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.200.10.100:8080/login.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("Name",loginInputs[0])); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("Password",loginInputs[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
httpresponse=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if("User Found".equals(response)){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(login.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(login.this, MainActivity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
PHP代码:
<?php
if (isset($_POST['Name']) && isset($_POST['Password'])) {
$name = $_POST['Name'];
$Password = $_POST['Password'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * FROM `userinfo` WHERE Name='$name' AND Password='$Password'");
if (mysql_num_rows($result)>0)
{
echo "User Found";
}
else {
echo "Not Found";
}
}
?>
我阅读了很多建议并试图改变很多东西但没有成功。无论如何,我认为由不匹配的字符串编码类型引起的问题,但不知道如何解决它。