2017-06-28 97 views
0

我想创建支持会话使用idhttp 10.5.7在德尔福XE的应用程序,但会话总是每次我调用请求时更改。会话没有维护使用indy 10 idhttp和德尔福XE

但是后来我在Delphi 2006中使用相同的代码,使用indy 10.1.5,会话保持成功,即使我多次调用请求时它只会创建1个会话。

如何在Delphi XE中解决这个问题?

unit Unit1; 

interface 

uses 
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
    Dialogs, IdCookieManager, IdBaseComponent, IdComponent, IdTCPConnection, 
    IdTCPClient, IdHTTP, StdCtrls,iduri,IdCookie; 

type 
    TForm1 = class(TForm) 
    HTTP: TIdHTTP; 
    Button1: TButton; 
    Memo1: TMemo; 
    procedure Button1Click(Sender: TObject); 
    procedure FormCreate(Sender: TObject); 
    private 
    function get_dataweb(url: string): string; 
    procedure OnNewCookie(ASender: TObject; ACookie: TIdCookieRFC2109; var VAccept: Boolean); 
    { Private declarations } 
    public 
     Stream : TStringStream; 
     cookie : TIdCookieManager; 
    { Public declarations } 
    end; 

var 
    Form1: TForm1; 

implementation 

{$R *.dfm} 

procedure TForm1.Button1Click(Sender: TObject); 
var hasil : string; 
begin 
    hasil := get_dataweb('http://localhost/web/tes.php'); 
end; 

procedure TForm1.FormCreate(Sender: TObject); 
begin 
    Stream := TStringStream.Create; 
    cookie := TIdCookieManager.Create; 
    cookie.OnNewCookie := OnNewCookie; 
    HTTP.CookieManager := cookie; 

end; 

procedure TForm1.OnNewCookie(ASender: TObject; ACookie: TIdCookieRFC2109; var VAccept: Boolean); 
begin 
    memo1.Lines.Add(ACookie.CookieText); 
end; 

function TForm1.get_dataweb(url:string):string; 
var hasil : string; 
begin 

    stream.Position  := 0; 
    stream.Size   := 0; 

    http.AllowCookies  := True; 
    http.HandleRedirects := True; 
    HTTP.ReadTimeout  := 0; 
    HTTP.ConnectTimeout := 0; 

    HTTP.Request.CustomHeaders.clear; 
    HTTP.Request.CustomHeaders.Add('user:user'); 
    HTTP.Request.CustomHeaders.Add('password:password'); 
    HTTP.request.useragent := 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'; 

    try 
    http.get(url,Stream); 
    hasil := Stream.DataString; 
    except 

    on E: EIdHTTPProtocolException do 
    begin 
     hasil := E.ErrorMessage; 
     result := hasil; 
     exit; 
    end; 
    on E: Exception do 
    begin 
     ShowMessage('Failed, ' + E.Message + #13#10 + ' ' + hasil); 
    end; 
    end; 

    result := hasil; 
end; 


end. 

3次我点击该按钮,3倍的新会话创建

3 times i clicked the button, 3 times new session created

+0

10.5.7很老了,现在的版本是10.6.2。无论如何,这显然是一个cookie问题。从10.1.5甚至10.5.7开始,cookie管理已经发生了很大变化,以更加贴近现代cookie的实践。所以很有可能,你的旧'TIdHTTP'要么丢弃这些cookies,要么不会将它们发送回服务器,因为它认为它们实际上并不匹配所做的请求。这将解释为什么每个请求都会创建新会话。我无法在10.6.2中重现此问题,会话将按预期重新使用。 –

回答

0

三江源建议雷米,我曾提升到印10.6.2和问题就解决了。我跟着this教程成功