使用来自C#的HTTP请求将NULL JSON发布到PHP服务器上

I'm trying to post a JSON string on a PHP page using HTTP response methods as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Web;


namespace http_requests
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/abc/products.php");
            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "POST";

            //using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            //{
            //    string json = new JavaScriptSerializer().Serialize(new
            //    {
            //        user = "Foo",
            //        password = "Baz"
            //    });

            //    streamWriter.Write(json);
            //    streamWriter.Flush();
            //    streamWriter.Close();

            //    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //    {
            //        var result = streamReader.ReadToEnd();
            //    }
            //}


            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/ABC/products.php");
            request.Method = WebRequestMethods.Http.Post;
            string DataToPost = new JavaScriptSerializer().Serialize(new
                {
                    user = "Foo",
                    password = "Baz"
                });
            byte[] bytes = Encoding.UTF8.GetBytes(DataToPost);
            string byteString = Encoding.UTF8.GetString(bytes);
            Stream os = null;
            //string postData = "firstName=" + HttpUtility.UrlEncode(p.firstName) +

            request.ContentLength = bytes.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            os = request.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);    
            //StreamWriter writer = new StreamWriter(request.GetRequestStream());
            //writer.Write(DataToPost);
            //writer.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //StreamReader reader = new StreamReader(response.GetResponseStream());
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                richTextBox1.AppendText("R : " + result);
                Console.WriteLine(streamReader.ReadToEnd().Trim()); 
            }
            //richTextBox1.Text = response.ToString();

        }
    }
}

I tried it in many different ways (converting to bytes too) but still posts a NULL array.

PHP Code:

<?php
$json = $_POST; 
if (isset($json)) {
    echo "This var is set so I will print.";
    //var_dump($json); 
    var_dump(json_decode(file_get_contents('php://input')));
    }





?>

When I try to get tha response from server and print onto a text box, it prints right:

R : This var is set so I will print.object(stdClass)#1 (2) { ["user"]=> string(3) "Foo" ["password"]=> string(3) "Baz" }

but i'm unable to check it on my PHP page, it says: This var is set so I will print.NULL

Not sure if its posting a JSON onto PHP or not, but it sure does posts a NULL. I want to see the JSON on PHP page, Any help would be appreciated.

Thank you, Revathy

dongque20030402
dongque20030402 没问题,很高兴我可以帮到你。
接近 6 年之前 回复
drju37335
drju37335 真棒,我明白你想说的是什么,它现在有效。非常感谢你的帮助@Steve:)
接近 6 年之前 回复
douji5746
douji5746 您的数据发布正常,但是当您在浏览器中查看oage时,它是一个完全独立的请求(获取请求,其中没有数据),因此您看到null。如果要从c#发布数据然后为网站访问者显示相同的数据,则需要将数据保存在服务器上的某个位置(文件/数据库)。
接近 6 年之前 回复
douzi2778
douzi2778 好的,这是好消息:你的c#代码运行得很好。坏消息是你有办法理解php和http的本质。
接近 6 年之前 回复
duanchao9559
duanchao9559 我正在尝试使用上面给出的代码在PHP页面上显示来自C#的POSTed数据。
接近 6 年之前 回复
du1913
du1913 我尝试了$HTTP_RAW_POST_DATA,但似乎没有用。给我'未定义的变量'错误。
接近 6 年之前 回复
doulizhi1247
doulizhi1247 “但是我无法在我的PHP页面上查看它”你是什么意思?你究竟想要“在我的PHP页面上查看”?-如果richTextBox1.AppendText(“R:”+result);正在将数据显示到文本框中,一切正常
接近 6 年之前 回复
dter8514
dter8514 你在这里有一些奇怪的东西...1)你使用的是php://输入很好,但也可以是全局的$_POST,根据一堆因素可能是空的。如果它是空的,它不会进入你的for循环。如果你启用了这个数据,那么访问这些数据的更好方法可能是$HTTP_RAW_POST_DATA。您可以通过php.ini中的always_populate_raw_post_data进行检查
接近 6 年之前 回复

1个回答



您的c#客户端代码没有任何问题,问题是访问浏览器中的网站是c#的单独请求 post,所以你什么也看不见。</ p>

根据我的评论,如果你想在post#之后在浏览器中看到数据,你需要保存并检索它。 / p>

下面是一个使用文本文件保存帖子数据并显示它的简单示例:</ p>

  // if post request 
if($ _SERVER ['REQUEST_METHOD'] =='POST'){
//从POST获取数据
$ data = file_get_contents('php:// input');
//保存到文件
file_put_contents('data .txt',$ data);
die('Saved');
}
// else如果是get请求(例如浏览器中的视图)
var_dump(json_decode(file_get_contents('data.txt')) );
</ code> </ pre>
</ div>

展开原文

原文

There is nothing wrong with your c# client side code, the problem is that visiting a site in your browser is a seperate request from the c# post, so you wont see anything.

As per my comment, if you want to see the data in a browser after a post i c#, you will need to save and retrieve it.

Here is a simple example using a text file to save post data and display it:

//if post request
if($_SERVER['REQUEST_METHOD']=='POST'){
    //get data from POST
    $data = file_get_contents('php://input');
    //save to file
    file_put_contents('data.txt', $data);
    die('Saved');
}
//else if its a get request (eg view in browser)
var_dump(json_decode(file_get_contents('data.txt')));

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐