簡體   English   中英

具有編碼UTF8的IdHTTPServer和IdHTTP

[英]IdHTTPServer and IdHTTP with Encoding UTF8

我正在使用TIdHTTPServerTIdHTTP測試本地主機服務器。 我在編碼UTF8數據時遇到問題。

客戶端:

procedure TForm1.SpeedButton1Click(Sender: TObject);
var
  res: string;
begin
  res:=IdHTTP1.Get('http://localhost/?msg=đi chơi thôi');
  Memo1.Lines.Add(res);
end;

服務器端:

procedure TForm1.OnCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  Memo1.Lines.Add(ARequestInfo.Params.Values['msg']); // ?i ch?i th?i

  AResponseInfo.CharSet := 'utf-8';
  AResponseInfo.ContentText := 'chào các bạn'; // chào các b?n
end;

我想發送đi chơi thôi並接收chào các bạn 但是,服務器收到?i ch?i th?i和客戶端接收chào các b?n

誰能幫我?

TIdHTTP完全按照您TIdHTTP傳輸URL,但是http://localhost/?msg=đi chơi thôi不是可以原樣傳輸的有效URL,因為URL僅包含ASCII字符。 可以按原樣使用未保留的ASCII字符,但是必須將保留和非ASCII字符進行字符集編碼為字節,然后必須將這些字節以%HH格式進行url編碼,例如:

IdHTTP1.Get('http://localhost/?msg=%C4%91i%20ch%C6%A1i%20th%C3%B4i');

您必須確保僅將有效的URL編碼URL傳遞給TIdHTTP

在此示例中,URL是硬編碼的,但是如果您需要更動態的TIdURI ,請使用TIdURI類,例如:

IdHTTP1.Get('http://localhost/?msg=' + TIdURI.ParamsEncode('đi chơi thôi'));

然后, TIdHTTPServer將按照您的期望對參數數據進行解碼。 默認情況下, TIdURITIdHTTPServer使用UTF-8。

發送響應時,僅設置CharSet ,而不設置ContentType 因此TIdHTTPServer會將ContentType設置為'text/html; charset=ISO-8859-1' 'text/html; charset=ISO-8859-1' ,覆蓋您的CharSet 您需要自己明確設置ContentType以便可以指定自定義CharSet ,例如:

AResponseInfo.ContentType := 'text/plain';
AResponseInfo.CharSet := 'utf-8';
AResponseInfo.ContentText := 'chào các bạn';

要么:

AResponseInfo.ContentType := 'text/plain; charset=utf-8';
AResponseInfo.ContentText := 'chào các bạn';

附帶說明一下, TIdHTTPServer是一個多線程組件。 OnCommand...事件是在輔助線程而不是主UI線程的上下文中觸發的。 因此,像您Memo1直接訪問Memo1並不是線程安全的。 您必須與主UI線程同步,以便安全地訪問UI控件,例如:

procedure TForm1.OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  msg: string;
begin
  msg := ARequestInfo.Params.Values['msg'];
  TThread.Synchronize(nil,
    procedure
    begin
      Memo1.Lines.Add(msg);
    end
  );
  ...
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM