无法从delphi中的TIdHTTP连接到TIdHTTPServer

Vik*_*sov 3 delphi indy httpserver

我有一个应用程序使用TIdHTTPServer,并TIdHTTP在Delphi和我有这样的代码:

// 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;
Run Code Online (Sandbox Code Playgroud)

这是OnCommandGet我的HTTPServer 的过程:

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

我只是不知道为什么这个程序不起作用:

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;
Run Code Online (Sandbox Code Playgroud)

如果我通过浏览器连接,我可以在浏览器中看到'Hello,user',但如果我尝试btnHTTPSendGetClick我的程序崩溃,没有例外或任何事情.任何人都可以帮我修复我的代码吗?

Rem*_*eau 5

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

这是一个常见的新手错误.您正在创建两个绑定,一个绑定到127.0.0.1:DefaultPort,另一个绑定到0.0.0.0:50001.您需要一个绑定,而是绑定到127.0.0.1:50001.

with HTTPServer1.Bindings.Add do begin
  IP := '127.0.0.1';
  Port := 50001;
end;
Run Code Online (Sandbox Code Playgroud)

要么:

HTTPServer1.Bindings.Add.SetBinding('127.0.0.1', 50001, Id_IPv4);
Run Code Online (Sandbox Code Playgroud)

要么:

HTTPServer1.DefaultPort := 50001;
HTTPServer1.Bindings.Add.IP := '127.0.0.1';
Run Code Online (Sandbox Code Playgroud)

话虽如此,您的服务器响应是不完整的.试试这个:

procedure TDataForm.HttpServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  AResponseInfo.ResponseNo := 200;
  AResponseInfo.ContentType := 'text/plain';
  AResponseInfo.ContentText := 'Hello, user';
end;
Run Code Online (Sandbox Code Playgroud)

  • 您无法使用关键部分保护对UI控件的访问权限,但这不起作用.您必须与主线程同步,以便主线程是直接访问UI的唯一线程.想要触摸UI的其他线程必须要求主线程代表他们这样做. (3认同)
  • @Roman_Bezjak:这意味着您的应用程序在繁忙的循环中被锁定,并且无法响应窗口消息... (2认同)