2012-01-20 40 views
1

如何從TWebRequest的內容字段中檢索實際的unicode字符串。當我嘗試閱讀TWebRequest的內容字段以獲取輸入的Unicode值時,我在文本中輸入了我看到的擾亂值而不是實際值。 我給出的輸入是Добро,但在內容字段中我看到的值是「обро。 Response contenttype設置爲text/html和charset ='UTF-8'。 任何人都可以知道爲什麼它沒有顯示在文本框中輸入的實際值以及如何修正。這點我是測試從TWebRequest的內容字段讀取unicode字符串

procedure TWebModule1.WebModule1HelloAction(Sender: TObject; 
    Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); 
var 
    s : string; 
    PageProducer1 : TPageProducer; 
begin 
    Response.ContentType := 'text/html;charset=UTF-8'; 
    s := Request.ContentFields.Text; 
    PageProducer1 := TPageProducer.Create(nil); 
    try 
    PageProducer1.HTMLFile := 'C:\Hello.tmpl'; 
    PageProducer1.OnHTMLTag := PageProducer1HTMLTag; 
    Response.Content := PageProducer1.Content + ' ' + 'Entered string:' + s; 
    finally 
    PageProducer1.Free; 
    end; 
end; 

Hello.tmpl

示例代碼只是有文本框和提交按鈕

回答

3

可以使用UTF8ToString功能,您的UTF-8字符串轉換爲UnicodeString

+0

感謝您的回覆,UTF8ToString完美工作,但它是因爲字符集設置爲UTF-8,字符串是ut8編碼,我們需要轉換爲unicode字符串。是否有任何方法或設置可以在Request對象上設置,以便它自動執行轉換 – ravi12

+2

HTTP有效內容是任意八位字節序列。內容類型(和內容編碼)字段告訴你如何解釋它。應用程序負責讀取正確的標題字段並以正確的方式處理負載。 –

+0

這將正常工作,但發出警告* W1058隱式字符串強制轉換,可能會將數據從'字符串'丟棄到'RawByteString'*。將其與使用RawContent而不是Content結合使用,警告消失。 –

0

您只需要使用TWebRequest.ContentRaw,它根據請求頭中定義的字符集返回帶有正確代碼頁的AnsiString。不幸的是,你將不得不手動處理內容。

要獲取字符串(UnicodeString),請使用TEncoding.UTF8.GetString(BytesOf(Request.RawContent)),如果您確定charset是UTF-8。另外,您可以檢查與頭的原始的contentType:

var ct: string; 
... 
ct := string(Request.GetFieldByName('Content-type')).ToUpper; 
if (Pos('CHARSET', ct) > 0) and (Pos('UTF-8', ct) > 0) then 
    Result := TEncoding.UTF8.GetString(BytesOf(Request.RawContent)) 
    else 
    Result := TEncoding.ANSI.GetString(BytesOf(Request.RawContent)); 

TWebRequest.ContentTWebRequest.ContentFields在我目前的)版本被竊聽。它們總是以ANSI編碼。 TWebRequest.EncodingFromContentType嘗試從TWebRequest.ContentType中提取字符集,但contentType中的charset部分在此處已被先前的代碼刪除。