Delphi Indy IdHTTPServer(IdHTTPServer) で UTF-8 を返す

 Indy の HTTP Server (TIdHttpServer)で、UTF-8 をレスポンスさせる

  1. procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);  
  2. var S: string;  
  3. begin  
  4.     S := '<html><head></head><body>Hello World!ハローワールド!</body></html>';  
  5.   
  6.     // UTF-8  
  7.     AResponseInfo.ContentStream := TStringStream.Create(S, TEncoding.UTF8);  
  8.     AResponseInfo.ContentType := 'text/html; charset=utf-8';  
  9.   
  10.     { 
  11.     // Shift-JIS 
  12.     AResponseInfo.ContentStream := TStringStream.Create(S, TEncoding.GetEncoding(932)); 
  13.     AResponseInfo.ContentType := 'text/html; charset=shift-jis'; 
  14.     }  
  15. end;  
AResponseInfo.ResponseText へそのまま記述するとデフォルトエンコードで処理されてしまうので、ContentStream へ直接投入し、ContentType へ charset でエンコードを記載しておく
charset の記述がないと、ブラウザは正しくエンコードを判断してくれない

コメント