Sending a string to a PHP page and having the PHP Page Display The String

喜夏-厌秋 提交于 2019-12-20 03:16:06

问题


What I'm trying to do is have my PHP page display a string that I've created through a function in my C# application, via System.Net.WebClient.

That's really it. In it' s simplest form, I have:

WebClient client = new WebClient();  
string URL = "http://wwww.blah.com/page.php";
string TestData = "wooooo! test!!";

byte[] SendData = client.UploadString(URL, "POST", TestData);

So, I'm not even sure if that's the right way to do it.. and I'm not sure how to actually OBTAIN that string and display it on the PHP page. something like print_r(SendData) ??

ANY help would be greatly appreciated!


回答1:


There are two halves to posting. 1) The code that posts to a page and 2) the page that receives it.

For 1) Your C# looks ok. I personally would use:

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

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

For 2) In your PHP page:

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

Read about reading post data in PHP here:

  • http://us.php.net/manual/en/wrappers.php.php
  • http://php.net/manual/en/reserved.variables.httprawpostdata.php



回答2:


Use This Codes To Send String From C# With Post Method

       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");
        }

and php page

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

        echo $msg;

    }

   ?>


来源:https://stackoverflow.com/questions/5036136/sending-a-string-to-a-php-page-and-having-the-php-page-display-the-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!