I have the following problem.
I have the method that sends json via POST:
public string request (string handler, string data)
{
WebRequest request = WebRequest.Create(baseUri + "/?h=" + handler);
request.Method = "POST";
request.ContentType = "text/json";
string json = "json=" + data;
byte[] bytes = Encoding.ASCII.GetBytes(json);
request.ContentLength = bytes.Length;
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
WebResponse res = request.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
lastResponse = sr.ReadToEnd();
return lastResponse;
}
When using the method on the server does not come data in POST. As if this code is not executed.
Stream str = request.GetRequestStream();
str.Write(bytes, 0, bytes.Length);
str.Close();
On the server i’m using following php script for debug:
<?php print_r($_POST); ?>
Also tried to write to the stream as follows:
StreamWriter strw = new StreamWriter(request.GetRequestStream());
strw.Write(json);
strw.Close();
The result – a zero response. In response comes an empty array.
The Problem is, that PHP does not “recognize” the
text/json-content type. And thus does not parse the POST-request-data. You have to use theapplication/x-www-form-urlencodedcontent-type and secondly you have to encode the POST-data properly:If you intend to supply the JSON-data directly you can leave the content-type to
text/jsonand pass the data directly asjson(without the “json=” part):But in that case you have to change your script on the PHP-side to directly read the post data: