我想使用$ _POST将数据从C#(Windows窗体应用程序)发布到PHP,但是在VS的Locals窗口中使用echo / var_dump检查时获得空值,同时显示带有已发布数据的ResponseStream的值。我不知道问题是否出在C#方法或PHP脚本中。
在Pass data from C# to PHP中,还有一些其他问题,在我的情况下,我将其应用如下。
PHP脚本(post.php):
<?php
// *** Use $_GET, the echo works when testing parameters from browser's address bar, but GET method in C# will fail.
//if(isset($_POST['data'])){
//if($_SERVER['REQUEST_METHOD'] == "POST"){
$data = $_POST['data'];
echo "Hello, ";
echo $data;
//}
?>
<!-- for debug purpose -->
<pre>
<?php
var_dump($_POST);
//print_r($_POST);
var_dump($_REQUEST);
?>
</pre>
C#方法:
public string SendPost(string url, string postData)
{
string webpageContent = string.Empty;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0x30 | 0xc0 | 0x300 | 0xc00);
// https://stackoverflow.com/questions/12506575/how-to-ignore-the-certificate-check-when-ssl
ServicePointManager.ServerCertificateValidationCallback +=
delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // **** Always accept
};
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
MessageBox.Show("Data has been posted.");
return webpageContent;
}
这是我如何调用方法:
String pData = "TestString";
SendPost("https://websites/post.php", String.Format("data={0}", pData));
在“本地”窗口中,“ webpageContent”的返回值:
Hello, TestString
在浏览器中,“ https://websites/post.php”:
Hello,
如何在PHP中保留/显示/使用从C#接收的值?