Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Json String to Remote PHP Script using Json.NET

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;
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 the server:

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

Any suggestions would be greatly appreciated.

Thanks

like image 786
cplusruss Avatar asked Jan 23 '11 06:01

cplusruss


1 Answers

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.

like image 152
jmort253 Avatar answered Oct 02 '22 11:10

jmort253