将数据从C#发送到php页面并在php上显示

时间:2018-07-09 09:42:21

标签: c# php

我正在使用altervista,它不允许直接与数据库建立连接,而只能通过服务器上存储的php脚本进行连接。在网上搜索,我找到了解决方案,使用Get或Post方法将数据从c#传递到php的URL。然后我用c#

编写了这段小代码
    private void SubmitData()
    {
        try
        {
            string url = "";
            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代码

<?php 
    if (isset($_POST['message']))
    {
        $msg = $_POST['message'];

        echo $msg;

    }
    else
    {
        echo "couldn't display data";
    }

   ?>

似乎从未向它发送过一些数据。 预先谢谢你。

0 个答案:

没有答案