我想发送字符串到我的php页面,我使用了这个网站中的一个答案
C#代码:
try
{
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();
}
catch (WebException)
{
MessageBox.Show("Please Check Your Internet Connection");
}
和php代码:
if (isset($_POST['message']))
{
$msg = $_POST['message'];
echo $msg;
}
但它只是一个空白页面。 任何人都可以告诉我有什么问题????
谢谢。答案 0 :(得分:0)
我不确定设置" message =" + data将在post数组中创建一个名为message的项:它可能只是创建一个带有内容" message = blahblahblajh"的无结果项。 您可以在php中执行此操作来测试此理论:
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
我没有使用HttpWebRequest,但您可以尝试使用webclient类:
string url = "http://localhost:8080/test.php";
string str = "test";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["message"] = str;
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
唉,我现在无法尝试这个,所以这是来自记忆和谷歌!
答案 1 :(得分:0)
如果您在运行代码后从浏览器访问该网页,则会出现一个空白页面,因为您的浏览器未发送帖子请求,您的应用程序是为了查看您的回复,在消息框或文本框中显示响应文本。即。
MessageBox.Show(responseText);