POST Json String for remote PHP script using Json.NET

I am encountering an unusually strange behavior when sending a Json string to a PHP web server. I am using a JsonTextWriter object to create a Json string. Then I send the Json string as a POST request. See Comments. The HTML response in the code returns the correct output, but when viewed in a browser, the web page displays either NULL or an 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; try { // 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 } try { // 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 server:

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

Any suggestions are welcome.

thanks

+6
json c # post php
source share
1 answer

Try using "application / json" as the content type. Also, check the request logs or perhaps trace port 80 if you can see what is being sent to the server in the request body.

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

+1
source share

All Articles