我在我的wp 7.1應用程序中有一個HttpWebRequest的小問題。應用程序通過POST方法將一些遊戲統計數據發送到php服務器,但服務器不會獲取它。 $ _POST數組保持爲空。藉助WireShark,我可以看到數據在發送到服務器的數據包中,但服務器不會收到任何數據。HttpWebRequest,post方法
下面是該數據發送方法的代碼:
private void SendStatisticsToServer()
{
if (this.stat.Name == String.Empty || Object.ReferenceEquals(this.stat.Name, null))
{
this.OnEmptyNameEvent();
}
else
{
HttpWebRequest request = WebRequest.Create(ADDRESS) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/plain";
request.AllowReadStreamBuffering = false;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallBack), request);
}
}
private void GetRequestStreamCallBack(IAsyncResult requestRes)
{
StringBuilder builder = new StringBuilder("user=");
builder.Append(this.stat.Name);
builder.Append("&won=");
builder.Append(this.stat.Won == true ? "1" : "0");
builder.Append("&scores=");
builder.Append(this.stat.Scores.ToString());
Byte[] byteArray = Encoding.UTF8.GetBytes(builder.ToString());
HttpWebRequest request = requestRes.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(requestRes);
stream.Write(byteArray, 0, byteArray.Length);
stream.Flush();
stream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult requestRes)
{
HttpWebRequest request = requestRes.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(requestRes) as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader streamRead = new StreamReader(stream);
String responseString = streamRead.ReadToEnd();
stream.Close();
streamRead.Close();
response.Close();
this.OnExitButtonPressedEvent(ButtonType.Exit);
}
(我是沒有意見的代碼抱歉,但我認爲這是不言自明)
由於你可以看到,它幾乎是從MSDN複製過來的。
這裏是-server代碼的PHP:
<?php
header('Content-type: text/plain');
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
// HTTP/1.0
header("Pragma: no-cache");
$logfile = 'postdata.txt';
$firstData = $_POST["user"];
$secondData = $_POST["won"];
$thirdData = $_POST["scores"];
$file = fopen($logfile, "a+");
fwrite($file, "Post received - data: firstData=". $firstData . "
secondData=" . $secondData . " thirdData=" . $thirdData . "\r\n");
fclose($file);
?>
正如你所看到的,這個服務器並沒有做太多 - 只接收數據,將其推入日誌-file。
這絕對不是服務器的bug,因爲使用Qt編寫的舊應用程序在相同的條件下工作正常並且$ _POST數組不是空的。
請問,請告訴我,哪裏可能出現錯誤?
目標平臺是WP 7.1。
預先感謝您的答案。
你說你用wireshark看了一下,服務器的迴應是什麼? – Pete
@Pete是的,我用wireshark檢查數據包的內容。根據wireshark,服務器響應是HTTP/1.1 200 OK。我也在應用程序中獲得了相同的響應(response.StatusCode總是返回OK) – user1415536
您能發佈wireshark看到的URL和標頭嗎? – Pete