I am encountering an unusually strange behavior when POSTing a Json string to a PHP webserver. I use the JsonTextWriter object to create the Json string. I then send the Json string as a POST request. Please see comments. The HTML response in the code is returning the correct output, but when viewed in a browser, the web page displays either NULL or array(0) { }.

private void HttpPost(string uri, string parameters)
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
{ // Send the Post Data 
    webRequest.ContentLength = bytes.Length;   
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);    

    Console.WriteLine(String.Format(@"{0}", byteString));     // <- This matches the Json object
catch (WebException ex)
{ //Handle Error }

{ // Get the response
    WebResponse webResponse = webRequest.GetResponse();
    if (webResponse == null) { return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    Console.WriteLine(sr.ReadToEnd().Trim());                // <- Server returns string response (full HTML page)
catch (WebException ex)
{ //Handle Error }

Relevant PHP code on the server:

$json = json_encode($_POST);   # Not 'standard way'

Any suggestions would be greatly appreciated.


Accepted Answer

Try using "application/json" as the content type. Also, check the request logs or maybe do a port 80 trace if you can to view what's being sent to the server in the request body.

You can also narrow the scope of the problem -- is it the C# code or the PHP code that's bad -- by writing a quick JQuery ajax function that sends some JSON to the PHP server. This isolation of the PHP code from the C# code will tell you if the PHP is at least working correctly. If it is, then the problem is in the C# code.

Written by jmort253
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki