我已经为这段代码苦苦挣扎了将近 16 个小时,结果对我来说仍然毫无意义。
我正在做的是制作一个将 POST 参数发送到 URL 的 Java 程序。我也在使用带有 Firefox 的表单测试相同的方法。
问题是,在 Firefox 上,我测试了正在发送的值并将其回显。我还根据我知道它应该相等的值测试该值,但是当 Java 发送该值时,它返回 false,但 Firefox 返回 true,这是为什么呢?
PHP代码:
$player = array('code' => "code");
$msg = "neither";
if(isset($_POST['player']))
{
$player = getPlayer(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME, DB_TABLE_NAME, $_POST['player']);
$msg = "?player=" . $_POST['player'] . " post";
}
function getPlayer($DbHost, $DbUsername, $DbPassword, $DbName, $DbTableName, $name)
{
try
{
$dsn = "mysql:host=$DbHost;dbname=$DbName"; //Data Source Name = MySQL
$dbc = new PDO($dsn, $DbUsername, $DbPassword); //Connect to DB
$query = "SELECT * FROM $DbTableName WHERE name = :name";
$result = $dbc->prepare($query); //Prepare query
if($name == "pathurs")
{
echo 'true:' . $name;
}
else
{
echo 'false:' . $name;
}
$result->bindParam(':name', $name, PDO::PARAM_STR);
$result->execute(); //Execute Query
while($row = $result->fetchObject()) //Loop through results
{
$array = array();
//Convert stdClass($row) to array($array)
foreach($row as $key => $value)
{
$array[$key] = $value;
}
$dbc = null;
return $array;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
echo "code:" . $player['code'] . $msg . $_POST['player'];
Java 代码:
public String getContent(String url, String params)
{
String result = "";
try
{
this.url = new URL(url);
try
{
URLConnection con = this.url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.println(params);
InputStream is = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line = "";
while((line = in.readLine()) != null)
{
result += line;
}
System.out.println(result);
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
return result;
}
火狐输出:
true:pathurscode:code?player=pathurs postpathurs
Java 程序输出:
false:pathurscode:?player=pathurs postpathurs
为什么当我比较时$name == "pathurs"
(在第 20 行的 PHP 代码中)它在 Firefox 中为真,但在 Java 中为假?看到它们都在 PHP 页面中测试并且它们都是字符串,并且它们都在 echo 中输出它们都等于一种形式,这对我来说没有意义'pathurs'
是不是我做错了什么?我目前无法理解它只会在 Java 发送信息而不是 Firefox 发送信息时发生的原因。我通过将 PDO 查询替换为:
$query = "SELECT * FROM $DbTableName WHERE name = 'pathurs'";
它在两个输出上都能完美运行。这让我更加困惑。我希望有人能帮帮忙!
提前致谢!