如何使用 idHTTP 连接设备

How to connect device with idHTTP

我有一些使用 HTTP 协议的设备。

连接消息必须像这样:

GET /cgi/proc/sound?1000&1000 HTTP/1.1
Host: 10.0.1.2
User-Agent: test
Authorization: Digest username="admin", realm="HTROM", nonce="5d6553aca400536fcd1dca1d467bc428", uri="/cgi/proc/sound?1000&1000", algorithm=MD5, response="7053664025903c9c1485a188023909bd", opaque="3115FB22", qop=auth, nc=00000001, cnonce="63d86b75894ca977"*

我的代码如下所示:

procedure TMainForm.FormCreate(Sender: TObject);
begin
  with idHTTP do begin
    HTTPOptions := HTTPOptions + [hoInProcessAuth];
    Request.BasicAuthentication := False;
    HandleRedirects := True;
    Request.URL := '/cgi/proc/sound?1000&1000';
    Request.UserAgent := 'test';
  end;
  //add result to memo
  meInfo.Text := idHTTP.Get('http://10.0.1.2'); 
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  idHTTP.Free;
end;    

procedure TMainForm.IdHTTPAuthorization(Sender: TObject;
  Authentication: TIdAuthentication; var Handled: Boolean);
begin
  Authentication.Username := 'admin';
  Authentication.Password := '555555';
  if Authentication is TIdDigestAuthentication then
  begin
    with Authentication.AuthParams do begin
      AddValue('realm', 'HTROM');
      AddValue('nonce', '527b004c29df30afd42c9dbf43dcb6d9');
      AddValue('algorithm', 'MD5');
      AddValue('response', '3f4f49f5adefafdf19ce9148103486af');
      AddValue('opaque', '60DB81DD');
      AddValue('qop', 'auth');
      AddValue('nc', '00000001');
      AddValue('cnonce', '669bcf2a9b1c9deb');
    end;
    TIdDigestAuthentication(IdHTTP.Request.Authentication).Uri := IdHTTP.Request.URL;
    TIdDigestAuthentication(Authentication).Method := 'GET';
    showmessage('onAuthorization: ' + Authentication.Authentication);
  end;
  Handled := True;
end;

我收到一个错误

HTTP /1.1 400 Bad Request

您没有正确请求 URL。您需要将 complete URL 传递给 TIdHTTP.Get(),而不是使用 TIdHTTP.Request.URL 属性,例如:

procedure TMainForm.FormCreate(Sender: TObject);
begin
  with idHTTP do
  begin
    HTTPOptions := HTTPOptions + [hoInProcessAuth];
    Request.BasicAuthentication := False;
    HandleRedirects := True;
    Request.UserAgent := 'test';
  end;
  //add result to memo
  meInfo.Text := idHTTP.Get('http://10.0.1.2/cgi/proc/sound?1000&1000');
end;

此外,在 OnAuthorization 事件中,您根本不需要手动填充摘要的 AuthParamsUriMethod 属性。 TIdDigestAuthentication 在收到来自服务器的身份验证请求时填充 AuthParams,而 TIdHTTP 在向服务器发送身份验证时填充 UriMethod 属性。

只需提供 UsernamePassword 即可,例如:

procedure TMainForm.IdHTTPAuthorization(Sender: TObject; Authentication: TIdAuthentication; var Handled: Boolean);
begin
  Authentication.Username := 'admin';
  Authentication.Password := '555555';
  Handled := True;
end;