所以我一直在学习如何制作一个C#应用程序,最近用LAMP服务器发送和接收参数但是我似乎已经碰壁了,我需要一些帮助来理解我在这里做错了什么。
这是一个简单的测试应用程序,它将两个参数(登录名和密码)发送到php文件,并根据参数是否正确接收响应。
private void btEntrar_Click(object sender, EventArgs e)
{
String login, senha, postData, requestMethod = "POST", contentType = "application/x-www-form-urlencoded", responseFromServer = null;
String urlLogin = "http://192.168.1.107/knowledgems/accounts/login.php";
login = tbLogin.Text;
senha = tbSenha.Text;
postData = "param1=" + login + "¶m2=" + senha;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
WebRequest request = WebRequest.Create(urlLogin);
WebResponse response;
Stream dataStream;
StreamReader reader;
//Send request
request.Method = requestMethod;
request.ContentType = contentType;
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//Get response
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
if (responseFromServer.Equals("SUCCESS"))
MessageBox.Show("Login efetuado.");
else
MessageBox.Show("Login não efetuado." + responseFromServer);
} //btEntrar
虽然一切看起来都是正确的,事实上我可以从我的php文件中得到回复,但我最终无法通过验证功能
(if (responseFromServer.Equals("SUCCESS")))
即使显示的响应正好是字符串“SUCCESS”,我似乎无法将responseFromServer字符串与“SUCCESS”进行比较,以检查是否一切都可以登录,因此它总是最终会读取else条件。
以下我也发布了我的php文件。
<?php
require_once 'connection.php';
header('Content-Type: application/form-data');
class User {
private $db;
private $connection;
function __construct(){
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
} //__construct
public function does_user_exist($username,$password){
$query = "SELECT * FROM users WHERE user_username = '$username' AND user_password = '$password'";
$result = mysqli_query($this->connection,$query);
if(mysqli_num_rows($result) > 0){
echo "SUCCESS";
} //if
else {
echo "ERRO&101";
} //else
mysqli_close($this->connection);
} //does_user_exist
} //class
$user = new User();
if (isset($_POST['param1'],$_POST['param2'])){
$username = $_POST['param1'];
$password = $_POST['param2'];
if(!empty($username) && !empty($password)){
//$encrypted_password = md5($password);
$user -> does_user_exist($username,$password);
}
else {
echo "ERRO&100";
} //else
} //if
?>
感谢您提前的时间,请帮忙!
Edit1:我的猜测是这种格式对于contentType来说不太合适,但我无法弄清楚这是什么样的正确方法。
答案 0 :(得分:2)
“成功”可能会在最后换行吗?看看是否有效:
if (responseFromServer.Trim().Equals("SUCCESS"))
{