我使用的是印地TIdHTTP与BasicAuthentication GET请求。
代码工作正常,但TIdHTTP第一401后不清除BasicAuthentication凭据,如果用户重新输入凭据,并重新发送请求时,右登录密码。 用户必须登录两次授权。
用户操作序列:
步骤1.用户类型错误的登录密码:ResponseCode = 401
步骤2.用户类型右登录密码:ResponseCode = 401
步骤3.用户类型右登录密码:ResponseCode = 200
在第二步的结果是一个错误,我想。 我该怎么办?
简单的代码:
var
IdHTTP1: TIdHTTP;
fLogin : string;
fPassword : string;
/// ...
if ( fLogin <> '' ) and ( fPassword <> '' )
then
begin
if ( IdHTTP1.Request.Username <> fLogin )
or
( IdHTTP1.Request.Password <> fPassword )
then
begin
IdHTTP1.Request.BasicAuthentication := True;
IdHTTP1.Request.Username := fLogin;
IdHTTP1.Request.Password := fPassword;
end;
s := IdHTTP1.Get( 'some_url' );
response_code := Idhttp1.response.ResponseCode;
case response_code of
200:
begin
// parse request data
end;
401 : Result := nc_res_Auth_Fail;
else Result := nc_res_Fail;
end;
end;
变化之前,您应该清楚您的身份验证
if Assigned(IdHTTP1.Request.Authentication) then
begin
IdHTTP1.Request.Authentication.Free;
IdHTTP1.Request.Authentication:=nil;
end;
或者你可以改变这种方式
if Assigned(IdHTTP1.Request.Authentication) then
begin
IdHTTP1.Request.Authentication.Username:=...;
IdHTTP1.Request.Authentication.Password:=...;
end else
begin
IdHTTP1.Request.BasicAuthentication:=True;
IdHTTP1.Request.Username:=...;
IdHTTP1.Request.Password:=...;
end;
你应该设置Request.UserName
和Request.Password
对每个请求的属性,然后使用OnAuthorization
事件如果服务器要求为他们获取新的凭证,如:
procedure TSomeClass.HttpAuthorization(Sender: TObject; Authentication: TIdAuthentication; var Handled: Boolean);
begin
if GetNewCredentials() then
begin
Authentication.UserName := ...;
Authentication.Password := ...;
Handled := True;
end;
end;
//...
var
IdHTTP1: TIdHTTP;
fLogin : string;
fPassword : string;
// ...
IdHTTP1.OnAuthorization := HttpAuthorization;
IdHTTP1.Request.BasicAuthentication := True;
IdHTTP1.Request.Username := fLogin;
IdHTTP1.Request.Password := fPassword;
s := IdHTTP1.Get( 'some_url' );
response_code := IdHTTP1.Response.ResponseCode;
case Response_Code of
200:
begin
// parse request data
end;
401 : Result := nc_res_Auth_Fail;
else
Result := nc_res_Fail;
end;
end;
TIdHTTP
会在内部不断重新尝试登录,触发OnAuthorization
每一次,直到服务器停止发送401答复或TIdHTTP.MaxAuthRetries
已经达成,以先到为准。