2
我學習Xamarin和PHP並排,我卡在這裏,因爲我無法從PHP接收正確的響應,我知道有一個錯誤,因爲我有意故意拼寫查詢。HttpClient總是返回從Xamarin類呼叫狀態代碼200
我使用XAMPP和Visual Studio 2017年,我在PHP代碼如下所示:
<?php
require_once('logger.php');
include('userobj.php');
$log = new Log("errors.log");
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$log->{'Write'}('Received a POST Request');
try
{
$data = json_decode(file_get_contents('php://input'), true);
foreach($data as $key =>$value)
{
$log->{'Write'}("array key: " . $key . " array value: " . $value);
}
$user = new User($data);
$log->{'Write'}("after createad: ");
$user->{'CreateNewUser'}();
}
catch (Exception $e)
{
http_response_code("400");
$log->{'Write'}("Error message\n"+$e->getMessage());
}
}
else
{
$log->{'Write'}("REQUEST NOT A POST");
}
?>
我一直在使用PHP內的一個try/catch試過,我知道它得到的錯誤,因爲我能寫我的日誌,那我打電話的樣子像這樣的方法:
public function CreateNewUser()
{
try
{
global $log, $config;
$log->{'Write'}("Creating Connection");
$connection = mysqli_connect($config->db_host,$config->db_username,$config->db_pwd,$config->db_dbname);
if($connection)
{
$log->{'Write'}("Creating new user");
$query = "INSERT INTOS users (name, lastname, policynumber, phone, email) ";
$query .= "VALUES ('$this->name', '$this->lastname', '$this->policynumber', '$this->phone', '$this->email');";
$result = mysqli_query($connection, $query);
if(!$result)
{
$log->{'Write'}('Query Failed on Create New User: ');
$log->{'Write'}(mysqli_error($connection));
die('Query Failed' . mysqli_error($connection));
}
}
else
{
$log->{'Write'}("Connection Failed");
die('Connection Failed');
}
}
catch(Exception $e)
{
http_response_code("400");
throw $e;
}
}
正如我所說,我有拼寫錯誤的查詢強制錯誤......終於我從Xamarin C#看起來通話像這樣:
public static async Task CreateUser(User user)
{
try
{
HttpClient _client = new HttpClient();
var content = JsonConvert.SerializeObject(user);
var response = await _client.PostAsync(url, new StringContent(content));
string error = response.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
如果我調試此代碼並查看變量「response」的值,它始終具有狀態代碼200,但我看到過類似的問題,但都使用「GET」。使用郵遞員由Jason的建議在評論中幫我看看這個問題
您是否使用郵遞員或類似工具測試了您的服務? – Jason
我只是試過郵差,我得到Status 200 OK,但是我可以在軟件的文本區域看到錯誤,錯誤是我寫到的一條消息:「查詢失敗,您的sql語法中有錯誤;檢查手冊.....「這實際上幫助我解決了這個問題,問題在於我將查詢的結果存儲在一個變量中並在if語句中使用它,感謝您讓我知道這個偉大的工具: ) –