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);
Any suggestions are welcome.
thanks
Russell
source share