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

C# 使用来自C的HTTP请求将空JSON发布到PHP服务器上#,c#,php,json,http,C#,Php,Json,Http,我尝试使用HTTP响应方法在PHP页面上发布JSON字符串,如下所示: 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

我尝试使用HTTP响应方法在PHP页面上发布JSON字符串,如下所示:

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();

        }
    }
}
我尝试了很多不同的方法(也转换成字节),但仍然发布了一个空数组

PHP代码:

<?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')));
    }





?>

当我尝试从服务器获取响应并打印到文本框时,它会正确打印:

R:设置这个变量是为了打印。对象(stdClass)#1(2){ [“用户”]=> 字符串(3)“Foo” [“密码”]=> 字符串(3)“Baz” }

但我无法在我的PHP页面上查看它,它说: 此变量已设置,因此我将打印.NULL

不确定它是否在PHP上发布JSON,但它确实发布了NULL。 我想在PHP页面上看到JSON,任何帮助都将不胜感激

谢谢,,
Revathy

您的c#客户端代码没有问题,问题是在浏览器中访问站点是与c#post不同的请求,因此您不会看到任何内容

根据我的评论,如果您想在发布后在浏览器中查看数据,则需要保存并检索数据

下面是一个使用文本文件保存并显示post数据的简单示例:

//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')));

你这里有一些奇怪的事情。。。1) 您正在使用php://input 这很好,但也有全局$u POST,它可能是空的,这取决于一系列因素。如果为空,则不会进入for循环。如果启用了$HTTP\u RAW\u POST\u数据,那么访问此数据的更好方法可能是$HTTP\u RAW\u POST\u数据。您可以通过always\u populate\u raw\u post\u data from php.ini
“但我无法在我的php页面上检查它”
这是什么意思?你到底是如何尝试
“在我的PHP页面上检查它”
?-如果
richTextBox1.AppendText(“R:+result”)将数据显示到文本框中,一切正常fine@LuckyBurger:我尝试了$HTTP\u RAW\u POST\u数据,但似乎不起作用。给我“Undefined variable”错误。@史蒂夫:我正试图使用上面给出的代码在PHP页面上显示来自C#的发布数据。@Revathysantanam好的,好消息是:您的C#代码工作正常。坏消息是,您需要了解php和http的本质。