我的 wp 7.1 应用程序中的 HttpWebRequest 有一个小问题。应用程序通过 POST 方法将一些游戏统计数据发送到 php 服务器,但服务器不获取它。$_POST 数组保持为空。在 WireShark 的帮助下,我可以看到数据在发送到服务器的数据包中,但服务器没有收到任何数据。
这是发送数据的方法的代码:
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 复制过来的。
这是 php -server 代码:
<?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);
?>
如您所见,该服务器并没有做太多事情——只接收数据并将其推送到日志文件中。
这绝对不是服务器的错误,因为用 Qt 编写的旧应用程序在相同条件下工作正常,并且 $_POST 数组不为空。
请你告诉我,哪里可能出现错误?
目标平台是 WP 7.1。
预先感谢您的回答。