Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi TIdhttp Post JSON?

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);
?>
like image 463
Atlas Avatar asked Aug 29 '12 10:08

Atlas


2 Answers

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.

like image 152
Remy Lebeau Avatar answered Sep 22 '22 23:09

Remy Lebeau


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);
?>
like image 26
sgomez Avatar answered Sep 18 '22 23:09

sgomez