我试图在我的xampp
网页上显示用C#HTML Post发送的值,这是我的代码:
private void sendHtmlData(UInt16 value) {
var postData = "Package" + value.ToString()
var data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/dashboard/");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
<!doctype html>
<html>
<head></head>
<body>
<? echo htmlspecialchars($_GET["Package"]); ?>
</body>
</html>
为什么这不起作用?例如,如果我调用函数,我的网页上什么都不会发生。
有两个失败:
1-Post数据的格式必须为key=value,但您只是将密钥与值连接在一起,您错过了"=",请更改
var postData = "Package" + value.ToString();
至
var postData = "Package=" + value.ToString();
此外,如果值有任何特殊字符,建议对其进行url编码:
var postData = "Package=" + Uri.EscapeDataString(value.ToString());
2-如果您将数据发送为POST,则必须将其检索为POST,而不是GET,更改
<? echo htmlspecialchars($_GET["Package"]); ?>
至
<? echo htmlspecialchars($_POST["Package"]); ?>