Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to TIdHTTPServer from TIdHTTP in delphi

I have an application with TIdHTTPServer and TIdHTTP in delphi and I have this code :

// This is for activating the HTTPServer - works as expected
HTTPServer1.Bindings.Add.IP := '127.0.0.1';
HTTPServer1.Bindings.Add.Port := 50001;
HTTPServer1.Active := True;

This is the OnCommandGet procedure of my HTTPServer :

procedure TDataForm.HttpServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  AResponseInfo.ContentText := 'Hello, user';
end;

And I just don't know why this procedure isn't working :

procedure TDataForm.btnHTTPSendGetClick(Sender: TObject);
var
  HTTPClient : TIdHTTP;
  responseStream : TMemoryStream;
begin
  HTTPClient := TIdHTTP.Create;
  responseStream := TMemoryStream.Create;
  try
    try
      HTTPClient.Get('http://127.0.0.1:50001', responseStream);
    except on e : Exception do begin
      showmessage('Could not send get request to localhost, port 50001');
    end;
    end;
  finally
    FreeAndNil(HTTPClient);
    FreeAndNil(responseStream);
  end;
end;

If I connect via browser I can see in the browser 'Hello, user', but if I try btnHTTPSendGetClick my program crashes with no exception or anything. Can anyone help me fix my code ?

like image 432
Viktor Anastasov Avatar asked May 04 '26 01:05

Viktor Anastasov


1 Answers

HTTPServer1.Bindings.Add.IP := '127.0.0.1';
HTTPServer1.Bindings.Add.Port := 50001;

This is a common newbie mistake. You are creating two bindings, one bound to 127.0.0.1:DefaultPort, and one bound to 0.0.0.0:50001. You need one binding instead, that is bound to 127.0.0.1:50001 instead.

with HTTPServer1.Bindings.Add do begin
  IP := '127.0.0.1';
  Port := 50001;
end;

Or:

HTTPServer1.Bindings.Add.SetBinding('127.0.0.1', 50001, Id_IPv4);

Or:

HTTPServer1.DefaultPort := 50001;
HTTPServer1.Bindings.Add.IP := '127.0.0.1';

With that said, your server response is incomplete. Try this instead:

procedure TDataForm.HttpServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  AResponseInfo.ResponseNo := 200;
  AResponseInfo.ContentType := 'text/plain';
  AResponseInfo.ContentText := 'Hello, user';
end;
like image 102
Remy Lebeau Avatar answered May 05 '26 14:05

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!