从Delphi登录网站

时间:2012-10-04 07:50:18

标签: delphi indy

我会问有人是否善意向我解释如何从Delphi应用程序登录网页。我在这里找到的所有例子都证明对我没用或者我做错了。我厌倦了搜索和无效的代码。

没有错误消息,我甚至将页面代码添加到Memo中,但似乎是登录页面的代码(不是帐户[dashboard]页面) - 似乎这段代码根本无法通过身份验证,我不知道为什么。

此代码有什么问题:

procedure Login;
var
 HTTP: TIdHTTP;
 Param: TStringList;
 S: String;
begin
 HTTP := TIdHTTP.Create(nil);
 HTTP.CookieManager := Main_Form.CookieManager;
 Param := TStringList.Create;
 Param.Clear;
 Param.Add('login=example');
 Param.Add('password=example');

try
 HTTP.Get ('http://www.filestrum.com/login.html');
 HTTP.Post('http://www.filestrum.com/login.html', Param);
 S := HTTP.Get ('http://www.filestrum.com/?op=my_account');
 Main_Form.Memo2.Lines.Add(S);
finally
  HTTP.Free;
  Param.Free;
end;
end;

或使用此版本:

procedure Login;
var
 HTTP: TIdHTTP;
 S: String;
begin  
 HTTP                             := TIdHTTP.Create(nil);
 HTTP.CookieManager               := Main_Form.CookieManager;
 HTTP.Request.BasicAuthentication := True;
 HTTP.Request.Username            := 'example';
 HTTP.Request.Password            := 'example';
 HTTP.AllowCookies                := True;
 HTTP.HandleRedirects             := True;

 S := HTTP.Get ('http://www.filestrum.com/?op=my_account');
 Main_Form.Memo2.Lines.Add(S);
end;

使用Delphi XE2并且无法使此代码运行并登录。它与XE3演示相同。就像我说的那样,我真的很厌倦寻找一些解决方案,浪费时间,没有任何东西。

请大家帮忙。真的需要它。

1 个答案:

答案 0 :(得分:9)

尝试这样的事情:

function Login: string;
var
  IdHTTP: TIdHTTP;
  Request: TStringList;
  Response: TMemoryStream;
begin
  Result := '';
  try
    Response := TMemoryStream.Create;
    try
      Request := TStringList.Create;
      try
        Request.Add('op=login');
        Request.Add('redirect=http://www.filestrum.com');
        Request.Add('login=example');
        Request.Add('password=example');
        IdHTTP := TIdHTTP.Create;
        try
          IdHTTP.AllowCookies := True;
          IdHTTP.HandleRedirects := True;
          IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
          IdHTTP.Post('http://www.filestrum.com/', Request, Response);
          Result := IdHTTP.Get('http://www.filestrum.com/?op=my_account');    
        finally
          IdHTTP.Free;
        end;
      finally
        Request.Free;
      end;
    finally
      Response.Free;
    end;
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;
end;