Sixers17
Sixers17

Reputation: 652

Unable to Send JSON Data from C# to PHP Server

I've been researching everywhere to solve this problem, but I keep running into a wall every time. Goal is to serialize data into a JSON string and send that data to a PHP file on the server. The end result is that the json_decode reads out null. I've been working on this for hours, any guidance or solutions from anyone would be greatly appreciated. Here's my code snippet.

private void sendData(string questionId, string youtubeUrl)
    {

        //fill in class data
        videoData vd = new videoData();
        vd.question_id = questionId;
        vd.video_path_on_server = videoId;

        //specifiy the url you want to send data to
        string phpurl = "http://questionoftheweek.local/video/save";

        //make request to url and set post properties
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(phpurl);
        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        try
        {
            //serialize
            DataContractSerializer ser = new DataContractSerializer(typeof(videoData));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, vd);

            string videodata = Encoding.UTF8.GetString(ms.ToArray());
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(videodata);
            writer.Close();
        }
        catch (Exception ex) {
            MessageBox.Show("Unable to send data: " + ex.Message);
        }

And here's the PHP code on the server I'm using:

<?php
$json = json_encode($_POST);
var_dump(json_decode($json));

Upvotes: 1

Views: 2101

Answers (1)

iamkrillin
iamkrillin

Reputation: 6876

Instead of using DataContractSerializer Use DataContractJsonSerializer or JavaScriptSerializer in your C# code

DataContractJsonSerializer Class Docs
JavaScriptSerializer Class Docs

Upvotes: 2

Related Questions