使用Delphi XE尝试使用Digest对合作伙伴的Web服务执行get()。
我已经将IdAuthenticationDigest
包含在uses子句中,该子句应该从我读过的内容中自动运行 - 但我必须遗漏一些东西,因为我得到了401 Unauthorized。
代码:
begin
// Init request:
IdHttp := TIdHttp.Create(nil);
try
idHttp.Request.ContentType := self.inputType; // 'application/xml'
idHttp.Request.Accept := self.outputType; //'application/json';
// Set request method:
idHttp.Request.Method := Method; // 'Get'
// Set username and password:
idHttp.Request.BasicAuthentication := False;
// IdHttp.Request.Username/Password also fails
IdHttp.Request.Authentication.Username := 'xx';
IdHttp.Request.Authentication.password := 'xx';
IdHttp.Request.ContentLength := Length(Body);
// Send request:
if Method = 'GET' then
Result := idHttp.Get(self.ServiceHost + URI)
else
if Method = 'POST' then
Result := idHttp.Post(self.ServiceHost + URI, SendStream);
finally
idHttp.Free;
end;
end;
答案 0 :(得分:4)
您需要设置Request.Username
和Request.Password
属性,而不是使用Request.Authentication
属性。另外,请勿设置Request.Method
或Request.ContentLength
属性。所有这三个属性都由内部TIdHTTP
管理。
// Init request:
IdHttp := TIdHttp.Create(nil);
try
idHttp.Request.ContentType := self.inputType; // 'application/xml'
idHttp.Request.Accept := self.outputType; //'application/json';
// Set username and password:
idHttp.Request.BasicAuthentication := False;
IdHttp.Request.Username := 'xx';
IdHttp.Request.Password := 'xx';
// Send request:
if Method = 'GET' then
Result := IdHttp.Get(self.ServiceHost + URI)
else
if Method = 'POST' then
Result := IdHttp.Post(self.ServiceHost + URI, SendStream);
finally
IdHttp.Free;
end;
答案 1 :(得分:4)
添加OnAuthorization事件,如下所示:
procedure TForm1.IdHTTP1Authorization(Sender: TObject;
Authentication: TIdAuthentication; var Handled: Boolean);
begin
Authentication.Username:='user';
Authentication.Password:='passs';
if Authentication is TIdDigestAuthentication then
begin
showmessage('onAuthorization: '+Authentication.Authentication);
TIdDigestAuthentication(IdHTTP1.Request.Authentication).Uri:=IdHTTP1.Request.URL;
TIdDigestAuthentication(Authentication).Method := 'GET';
end;
Handled:=true;
end;
有时indy错过了一些必要的信息。在我的情况下,我正在连接到Tomcat服务器,但是当发送摘要参数身份验证信息时,这需要Get方法。
答案 2 :(得分:1)
您还需要设置 hoInProcessAuth 标志,以便执行GET。
idHttp.HTTPOptions := idHttp.HTTPOptions + [hoInProcessAuth];