Indy总是返回ResponseCode 200 - 即使登录失败

时间:2016-02-15 22:19:19

标签: delphi login delphi-xe indy10

我正在使用Indy 10.5.7

我最近看到过如何使用Indy登录具有有效凭据的网站。现在我可以执行搜索并返回我需要的结果。

但是,我仍有问题。我必须理所当然地认为我已成功登录页面重定向,因为我无法获得200以外的响应代码。

我的意思是,我想处理用户输入用户名或密码输入错误的情况,并至少告知他们有什么不妥。

为了这个问题,我把Indy设置如下......

var
  client      : TidHTTP;
  cookieMan   : TidCookieManager;
  params      : TStringList;
  response    : string;

begin
  cookieMan := TidCookieManager.Create(nil);
  client := TidHTTP.Create(nil);
  params := TStringList.Create;

  try
    with client do
    begin
      ProtocolVersion     := pv1_1;
      HTTPOptions         := [hoForceEncodeParams, hoKeepOrigProtocol];
      AllowCookies        := True;
      cookieManager       := cookieMan;
      HandleRedirects     := True;
      //Request.UserAgent   := 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0';
      //Request.UserAgent   := 'Mozilla/5.0 (Windows NT 6.3; WOW64)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36';
      Request.UserAgent   := 'Mozilla/5.0 (X11; U; Linux i586; en-US; rv:1.7.3) Gecko/20040924 Epiphany/1.4.4 (Ubuntu)';
      //OnRedirect          := handleRedirect;
    end;

    params.Add('username=aFakeUser');
    params.Add('password=aFakePass');

    try
      response := client.Post('http://assurance.redtractor.org.uk/rtassurance/services.eb', params);
      mmoResponseCodes.Lines.Add('No exception, INDY OK ' + intToStr(client.ResponseCode));         // << ALWAYS returns 200
      // do nothing with params ...  just to try to raise any exception

      // I need to be logged in to reach the next page, this is a search page ...
      response := client.Post('http://assurance.redtractor.org.uk/rtassurance/services/cr_services/checking.eb', params);
      mmoResponseCodes.Lines.Add('Still no exception, INDY OK ' + intToStr(client.ResponseCode));   // << ALWAYS returns 200
      mmoResponse.Text := response;

    except
      on e: EIdHTTPProtocolException do
      begin
        // No exception raised, I expected e.ErrorCode = 401
        mmoResponseCodes.Lines.Add('Post Indy Error ' + intToStr(e.ErrorCode) + ' >>> ' + e.Message);
      end;
    end;

  finally
    client.Free;
    cookieMan.Free;
    params.Free;
  end;
end;

我真的不知道我做错了什么。我已经看到Remy指出要捕获异常并查看e.ErrorCode的很多帖子,但我不能用我故意伪造的凭据引发异常。

我可以请你指出正确的方向,并指出我做错了吗?

1 个答案:

答案 0 :(得分:6)

您正在使用基于HTML的身份验证(已发布的HTML网络表单),而不是基于HTTP的身份验证(HTTP Authentication请求标头)。

从HTTP角度来看,HTML网络表单的失败身份验证仍然可以在HTTP层报告为成功的200回复​​。客户端请求了URL,服务器发送了一个HTML页面作为回复。 HTML声明身份验证是成功还是失败是无关紧要的,HTTP只是一种传输,它并不关心正在传递的特定内容。仅在发生HTTP层错误时才会报告HTTP错误。如果HTML身份验证失败,生成的HTML页面通常会再次包含错误消息和/或登录HTML webform。

因此,在这种情况下,您将获得HTTP 200回复​​,因为HTTP成功完成了它的工作。您将不得不分析返回的实际HTML以了解身份验证是否真的成功或失败。 HTTP层没有任何指示方式。