Anybody getting JSON to work with TIdHttp ?
The PHP always return NULL in the $_POST
, am I doing anything wrong ?
Delphi source:
http := TIdHttp.Create(nil);
http.HandleRedirects := True;
http.ReadTimeout := 5000;
http.Request.ContentType := 'application/json';
jsonToSend := TStringStream.Create('{"name":"Peter Pan"}');
jsonToSend.Position := 0;
Memo1.Lines.Text := http.Post('http://www.website.com/test.php', jsonToSend);
jsonToSend.free;
http.free;
PHP source:
<?php
$value = json_decode($_POST);
var_dump($value);
?>
You can't use a TStringList
to post JSON data. TIdHTTP.Post()
will encode the TStringList
contents in a way that breaks the JSON data. You need to put the JSON data into a TStream
instead. TIdHTTP.Post()
will transmit its contents as-is. Also, don't forget to set the TIdHTTP.Request.ContentType
property so the server knows you are posting JSON data.
You need to define a post variable, try this code (I have added "json" var to your code):
Delphi code:
http := TIdHttp.Create(nil);
http.HandleRedirects := true;
http.ReadTimeout := 5000;
jsonToSend := TStringList.create;
jsonToSend.Text := 'json={"name":"Peter Pan"}';
Memo1.Lines.Text := http.Post('http://www.website.com/test.php', jsonToSend);
jsonToSend.free;
http.free;
PHP source:
<?php
$value = json_decode($_POST['json']);
var_dump($value);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With