我在delphi中有一个TIdHTTPServerTIdHTTP的应用程序,并且我有以下代码:

// 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;


这是我的HTTPServer的OnCommandGet过程:

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


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

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;


如果我通过浏览器连接,则可以在浏览器中看到“用户您好”,但是如果我尝试btnHTTPSendGetClick,则程序将毫无例外地崩溃。谁能帮我修复我的代码?

最佳答案

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;


要么:

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


要么:

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


话虽如此,您的服务器响应仍不完整。尝试以下方法:

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

10-08 09:15