2012-12-23 54 views
6

我使用delphi和python实现了相同的代码(发布表单)。 Python代码完美工作,但delphi代码失败。在python中,我可以简单地编写httplib2.debuglevel=4来查看实际发送到服务器的内容。但我不知道如何在delphi中打印内容。如何跟踪原始请求和响应内容TIdHttp

def python_request_data(url, cookie, data): 
    httplib2.debuglevel = 4 
    conn = httplib2.Http() 
    conn.follow_all_redirects = True 
    headers = {'Cookie': cookie, 'Content-Type': 'application/x-www-form-urlencoded'} 
    response, contents = conn.request(url, 'POST', data, headers=headers) 

procedure DelphiRequestData(const Url, Cookie, Data: string); 
var 
    Client: TIdHttp; 
    Params: TStringList; 
    Response: string; 
begin 
    Client := TIdHttp.Create(nil); 
    try 
    Client.HTTPOptions := [hoKeepOrigProtocol]; 
    Client.Request.CustomHeaders.AddValue('Cookie', Cookie); 
    Params := TStringList.Create; 
    try 
     Params.QuoteChar := #0; 
     Params.Delimiter := '&'; 
     Params.DelimiterText := Data; 
     Client.Request.ContentType := 'application/x-www-form-urlencoded'; 
     Client.Request.ContentLength := Length(Params.DelimitedText); 
     Response := Client.Post(Url, Params); 
    finally 
     Params.Free; 
    end; 
    finally 
    Client.Free; 
    end; 
end; 

任何提示表示赞赏。

+0

感谢@bummi的提示。看到日志后,我看到TIdHttp发送的协议版本不正确,除非我设置Client.HTTPOptions:= [hoKeepOrigProtocol]。 – stanleyxu2005

回答

4

您可以使用TIdLogDebug作为您的IdHttp的拦截。
Events OnSend和OnReceive将在Array或TBytes中传递所需的信息。

+4

'TIdLogDebug'将其数据直接输出到调试器事件日志。如果你想在自己的代码中捕获数据,可以使用'TIdLogEvent'来代替。它的'OnSent'和'OnReceived'事件提供的数据是String值,而不是'TBytes'值(你正在考虑'TIdLogBase'的底层Send()'和Receive()'方法)) 。 –