doyz51819 2015-01-16 12:59
浏览 77
已采纳

使用来自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

  • 写回答

1条回答 默认 最新

  • doumu5662 2015-01-16 14:57
    关注

    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')));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入