【问题标题】:Sending a string to a PHP page and having the PHP Page Display The String将字符串发送到 PHP 页面并让 PHP 页面显示字符串
【发布时间】:2011-02-17 23:46:43
【问题描述】:

我想要做的是让我的 PHP 页面显示一个字符串,该字符串是我通过 C# 应用程序中的一个函数通过 System.Net.WebClient 创建的。

原来如此。以最简单的形式,我有:

WebClient 客户端 = 新 WebClient(); 字符串 URL = "http://www.blah.com/page.php"; string TestData = "wooooo! test!!"; byte[] SendData = client.UploadString(URL, "POST", TestData);

所以,我什至不确定这是否是正确的方法。我不确定如何实际获取该字符串并将其显示在 PHP 页面上。类似 print_r(SendData) ??

任何帮助将不胜感激!

【问题讨论】:

  • 如果您可以控制 php 页面,您可以将 TestData 作为 url 中的查询字符串参数发送...然后在 php 页面中您将使用它。
  • 这没什么意义。这个 C# 应用程序在哪里运行?您希望它向一个 PHP 页面发送一个字符串,然后您希望在同一页面上显示该字符串?在不同的页面上?显示到哪个浏览器?
  • 我知道这很荒谬。但是,是的;我希望 C# 应用程序将字符串发送到完全不同的服务器(我可以访问)上的 PHP 页面,稍后我可以在其中进一步操作该字​​符串(从中提取内容,将提取的数据放入数据库等)。
  • 这并不荒谬。它被称为网络服务;)

标签: c# php webclient


【解决方案1】:

使用此代码通过 Post 方法从 C# 发送字符串

       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;

    }

   ?>

【讨论】:

  • 谢谢老兄。我也需要这个。
【解决方案2】:

发帖分为两部分。 1) 发布到页面的代码和 2) 接收它的页面。

对于 1) 你的 C# 看起来不错。我个人会使用:

string url = "http://wwww.blah.com/page.php";
string data = "wooooo! test!!";

using(WebClient client = new WebClient()) {
    client.UploadString(url, data);  
}

对于 2) 在您的 PHP 页面中:

if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
    $postData = file_get_contents('php://input');
    print $postData;
}

在此处阅读有关在 PHP 中读取帖子数据的信息:

【讨论】:

  • 谢谢!我得到了 C# 代码,但在 PHP 代码中 - 我收到它后仍然无法在页面上显示字符串.. 这可能是我的一个愚蠢的错误,但它让我发疯:((得到一个空白页)跨度>
  • 然后我会尝试先通过查询字符串发送数据,看看你是否可以让它工作(例如,使用 c# 将数据发送到wwww.blah.com/page.php?message=wooooo!test!! 然后使用 php print $_GET[" fmessage"];)。一旦你有这个工作,我会回到 POST 问题。
猜你喜欢
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多