doyz51819
doyz51819
2015-01-16 12:59

使用来自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 doumu5662 6年前

    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')));
    
    点赞 评论 复制链接分享