枚举 TWebRequest HTTP 头字段 [英] Enumerate TWebRequest HTTP header fields
问题描述
是否可以转储 TWebRequest(和 TWebResponse)对象的所有标头字段?目前我使用 GetFieldByName() 并使用 Writeln() 打印它们,但这仅在我已经知道标题字段的名称时才有效.我正在寻找一种方法来获取所有标题字段名称来枚举每个字段,但我没有找到任何方法来做到这一点.
is it possible to dump all the header fields of a TWebRequest (and TWebResponse) object? At the moment I use GetFieldByName() and print them with Writeln() but this works only if I already know the name of the header field. I'm looking for a way to obtain all header field names to enumarate each field but I didn't find any method to do that.
我编写了一个 REST 数据快照控制台应用程序,并希望将所有 HTTP 请求/响应记录到控制台.
I wrote a REST datasnap console application and wants to log all HTTP requests/responses to console.
推荐答案
AFAIK it is not possibile (Delphi XE2).
AFAIK it is not possibile (Delphi XE2).
我使用了一些技巧来访问原始标题.然而,这真的很脏!使用风险自负!
I've used a little trink to have access to the raw headers. However, this is really dirty! Use at you own risk!
实际的类请求类是 TIdHTTPAppRequest(警告:不同类型的 webbroker 应用程序可能会有所不同.我没有用不同类型的数据快照应用程序测试此代码).
The actual class request class is the TIdHTTPAppRequest (WARNING: Could be different for different type of webbroker app. I''ve not tested this code with different kind of datasnap app).
所以诀窍是:
声明一个类似于下面的类助手:
Declare a class helper similar to the following:
TIdHTTPAppRequestHelper = class helper for TIdHTTPAppRequest
public
function GetRequestInfo: TIdEntityHeaderInfo;
end;
implementation
function TIdHTTPAppRequestHelper.GetRequestInfo: TIdEntityHeaderInfo;
begin
Result := FRequestInfo;
end;
这样你就可以使用这个助手来访问受保护的 FRequestInfo 字段.
In this way you can use this helper to have acccess to the protected FRequestInfo field.
在 OnAction 事件处理程序中,您可以使用以下代码获得所有标题名称:
In the OnAction event handler you can use the following code to have all the headers names:
procedure Twm.wmWebActionItem1Action(Sender: TObject; Request: TWebRequest;
Response: TWebResponse; var Handled: Boolean);
var
HeadersCount: Integer;
I: Integer;
sw: TStreamWriter;
begin
Response.ContentType := 'text/plain';
Response.ContentStream := TMemoryStream.Create;
sw := TStreamWriter.Create(Response.ContentStream);
try
HeadersCount := TIdHTTPAppRequest(Request).GetRequestInfo.RawHeaders.Count;
for I := 0 to HeadersCount - 1 do
sw.WriteLine(TIdHTTPAppRequest(Request).GetRequestInfo.RawHeaders.Names[I]);
finally
sw.Free;
end;
Handled := True;
end;
然而,TWebRequest 不允许读取原始标头是很糟糕的.应该改!
However, it is bad that TWebRequest do not allows to read the raw headers. That should be changed!
这篇关于枚举 TWebRequest HTTP 头字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!