Delphi TIdhttp Post JSON?


Delphi TIdhttp Post JSON?

有人能用JSON处理TIdHttp吗?

PHP在$_POST中总是返回NULL,我做错了什么吗?

Delphi来源:

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来源:

<?php
$value = json_decode($_POST);
var_dump($value);
?>

不能使用TStringList发布JSON数据。TIdHTTP.Post()将以破坏JSON数据的方式对TStringList内容进行编码。您需要将JSON数据放入TStream中。CCD_ 6将按原样发送其内容。另外,不要忘记设置TIdHTTP.Request.ContentType属性,以便服务器知道您正在发布JSON数据。

您需要定义一个post变量,请尝试以下代码(我在代码中添加了"json"var):

Delphi代码:

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来源:

<?php
$value = json_decode($_POST['json']);
var_dump($value);
?>