Delphi TIdhttp发布JSON?

Atl*_*las 6 php delphi json indy

有人得到JSON与TIdHttp一起工作吗?

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

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;
Run Code Online (Sandbox Code Playgroud)

PHP来源:

<?php
$value = json_decode($_POST);
var_dump($value);
?>
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 8

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

  • 不过,你的回答是正确的答案.要发布原始JSON数据并使用原始PHP代码接受它,需要使用`TStream`而不是`TStringList`,就像你展示的那样.您的答案中唯一的错误是您将`Request.ContentEncoding`设置为UTF-8,这是错误的,因为UTF-8不是有效的内容编码.它属于`Request.CharSet`. (3认同)
  • 我做了一些研究,发现原来的PHP脚本在使用`$ _POST`时是错误的.这仅适用于发布JSON流不存在的名称/值对.PHP脚本需要使用`php:// input`来访问原始JSON数据,例如:`$ value = json_decode(file_get_contents('php:// input'));` (3认同)
  • 因为接受了PHP巫术,我放弃了这个问题. (2认同)