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

NULL JSON posted onto PHP server using HTTP requests from C#

我正在尝试 post PHP 页面上的 JSON 字符串,使用 HTTP 响应方法如下:

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

        }
    }
}

我尝试了很多不同的方法(也转换为字节)但仍然post是一个 NULL 数组。

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 :此变量已设置,因此我将 print.object(stdClass)#1 (2) { ["user"]=> 字符串(3) "Foo" ["password"]=> 字符串(3) "Baz" }

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

不确定它是否 post 将 JSON 放到 PHP 上,但它肯定 post 是 NULL。 我想在 PHP 页面上查看 JSON,如有任何帮助,我们将不胜感激。

谢谢, 雷瓦西

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

根据我的评论,如果您想在 post i c# 之后在浏览器中查看数据,您需要保存和检索它。

下面是一个使用文本文件保存 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')));