将字符串从c#应用程序发送到php页面

本文关键字:php 页面 应用程序 字符串 | 更新日期: 2023-09-27 17:50:04

我想发送字符串到我的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;
}

但它只是一个空白页。谁能告诉我出了什么问题????

谢谢。

将字符串从c#应用程序发送到php页面

我不确定设置"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();

唉,我不是在一个位置尝试这个时刻,所以这是从记忆和谷歌!

如果你在运行代码后从浏览器访问网页,你会得到一个空白页面,因为你的浏览器没有发送post请求,你的应用程序是,为了查看你的响应,只是在消息框或文本框中显示响应文本。例如

MessageBox.Show(responseText);