TIdHttp.Post - 不能得到UTF-8编码(TIdHttp.Post - can'

2019-08-01 17:50发布

我怎么能强迫TIdHttp.post方法返回以UTF-8编码的网页? 我试图http.Request.ContentEncoding := 'UTF-8'但它行不通。 这里是我的代码:

procedure TeUpdateNews.Check;
var url: string;
    Http: TIdHttp;
    SS: TStringStream;
    param: TStringList;
    SWIDESTRING: WideString;
begin
  http := TIDHttp.Create(nil);
  http.HandleRedirects := true;
  http.ReadTimeout := 5000;
  http.Request.ContentEncoding := 'UTF-8';

  param := TStringList.create;
  param.Clear;

  url := CONST_SOME_WWW;

  try
    SS := TStringStream.Create;
    try
      SWIDESTRING := http.Post(url, param);

       // it's not getting utf-8!
       ShowMessage(SWIDESTRING); 
    finally
      SS.Free;
      param.free;
    end;
  finally
    Http.Free;
  end;
end;

Answer 1:

好吧,我发现我做了什么错。 如果有人将搜索:

您需要设置在构造函数中的TStringStream编码,所以它应该是这样的:

try
  // this is it :-)
  SS := TStringStream.Create('', TEncoding.UTF8);
  try
    // using overloaded post method this time
    // it writes return in the ss stream
    http.Post(url, param, ss);

     // now it's getting utf-8, baby!
     ShowMessage(ss.DataString); 


Answer 2:

var

  ds: TIdMultipartFormDataStream;

begin

  ds := TIdMultipartFormDataStream.Create;

  try

    ds.AddFormField('test', UTF8Encode('äöüß'), 'utf-8').ContentTransfer := '8bit';

    try

      ShowMessage(HTTP.Post('http://mysite.net/test.php', ds));

    except

    end;

  finally

    FreeAndNil(ds);

  end;

end;


文章来源: TIdHttp.Post - can't get utf-8 encoding