TIdHttp.Post - can't get utf-8 encoding

2019-04-09 02:17发布

How can I force TIdHttp.post method to return the web page encoded in utf-8? I tried http.Request.ContentEncoding := 'UTF-8' but it doesn'twork. Here's my code:

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;

2条回答
祖国的老花朵
2楼-- · 2019-04-09 02:54

Ok, I found what i've done wrong. In case anybody would search:

You need to set the TStringStream encoding in constructor, so it should be like:

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); 
查看更多
放荡不羁爱自由
3楼-- · 2019-04-09 03:00
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;
查看更多
登录 后发表回答