从c#应用程序发送一个字符串到PHP
本文关键字:一个 字符串 PHP 应用程序 | 更新日期: 2023-09-27 17:51:16
我想从我的c#应用程序发送字符串到我的PHP页面,我尝试了一些不同的解决方案,我在互联网上发现。其中之一是:
c#代码: string url = "http://localhost:8080/test.php";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message=" + str;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
和PHP代码:
foreach($_POST as $pdata)
echo $pdata;
但这只是一张空白页。我不知道是什么问题
我已经很长时间没有使用c#了,但这应该是解决方案:
string url = "http://localhost:8080/test.php";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message=" + str;
UTF8Encoding utf8 = new UTF8Encoding();
byte[] postBytes = utf8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(resStream);
string responseText = sr.ReadToEnd();
我所做的是将编码从ASCII更改为UTF8。UTF8是application/x-www-form-urlencoded
所期望的。
对于你的php,我假设你的foreach方法上有左括号和右括号。
编辑:好吧,我注意到你c#中的一个错误。你收到了两次响应流。这可能会导致一些错误,但这是我如何构建我的php:
<?php
foreach($_POST as $key => $value){
echo $value . "<br>";
}
?>