Delphi TIdhttp Post JSON?

2019-02-09 20:20发布

问题:

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

回答1:

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.



回答2:

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