如何使用 TIdHTTP post 向 PHP 服务器发送 UTF-8 编码请求?

How to post an UTF-8 encoded request to a PHP server with TIdHTTP?

当我将字符串发送到 PHP 页面时,它工作正常。

问题是当我使用阿拉伯语如“محمد”时,我得到的结果如“؟؟؟”。这是我的 Delphi 代码:

var
  s: string;
  server: TIdHttp;
begin
  s := 'محمد';
  server := TIdHttp.Create;
  server.Post('http://mywebsite.com/insert_studint.php?name1=' + s);
  server.Free;
end;

我的PHP代码:

<?php
    $name1=$_post['name1'];
    echo $name1;
?>

如何将我的请求编码为 UTF-8 以便在我的 PHP 服务器上获得正确的结果?

这不是 URL 字符串查询参数由 TIdHTTP class. The first parameter of the Post 方法处理的方式,只是目标 URL。 URL 字符串查询参数需要作为流或字符串列表集合作为此方法的第二个参数传递。您还需要在代码中指定请求编码,其余部分将在内部处理 class。试试这个:

var
  Server: TIdHTTP;
  Params: TStrings;
begin
  Server := TIdHTTP.Create;
  try
    { setup the request charset }
    Server.Request.Charset := 'utf-8';
    { create the name=value parameter collection }
    Params := TStringList.Create;
    try
      { add the name1 parameter (concatenated with its value) }
      Params.Add('name1=محمد');
      { do the request }
      Server.Post('http://mywebsite.com/insert_studint.php', Params);
    finally
      Params.Free;
    end;
  finally
    Server.Free;
  end;
end;