Delphi TIdhttp Post JSON?

Atlas picture Atlas · Aug 29, 2012 · Viewed 17.5k times · Source

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);
?>

Answer

Remy Lebeau picture Remy Lebeau · Aug 30, 2012

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.