【问题标题】:NULL JSON posted onto PHP server using HTTP requests from C#使用来自 C# 的 HTTP 请求将 NULL JSON 发布到 PHP 服务器
【发布时间】:2015-01-16 12:59:09
【问题描述】:

我正在尝试使用 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();

        }
    }
}

我尝试了许多不同的方式(也转换为字节),但仍然发布了一个 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 : 这个 var 已设置,所以我将 print.object(stdClass)#1 (2) { [“用户”]=> 字符串(3)“Foo” [“密码”]=> 字符串(3)“巴兹” }

但我无法在我的 PHP 页面上查看它,它说: 这个 var 已经设置好了,所以我会 print.NULL

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

谢谢你, 生气

【问题讨论】:

  • 好吧,你这里有一些奇怪的东西...... 1)你正在使用 php://input 这很好,但全局 $_POST 可能是空的,这取决于一堆因素。如果它是空的,它不会进入你的 for 循环。如果您启用了 $HTTP_RAW_POST_DATA ,访问此数据的更好方法可能是 $HTTP_RAW_POST_DATA。您可以通过 php.ini 中的 always_populate_raw_post_data 进行检查
  • "but i'm unable to check it on my PHP page" 这是什么意思?你究竟是如何尝试"check it on my PHP page"? - 如果richTextBox1.AppendText("R : " + result); 正在将数据显示到文本框中,则一切正常
  • @LuckyBurger:我试过 $HTTP_RAW_POST_DATA,但似乎不起作用。给我“未定义的变量”错误。
  • @Steve:我正在尝试使用上面给出的代码在 PHP 页面上显示来自 C# 的 POST 数据。
  • @RevathySanthanam 好的,这是个好消息:您的 c# 代码运行良好。坏消息是你有办法理解 php 和 http 的本质。

标签: c# php json http


【解决方案1】:

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

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

这是一个使用文本文件保存帖子数据并显示它的简单示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    相关资源
    最近更新 更多