无法从delphi中的TIdHTTP连接到TIdHTTPServer

时间:2014-05-28 15:59:25

标签: delphi indy httpserver

我在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;

如果我通过浏览器连接,我可以在浏览器中看到“Hello,user”,但是如果我尝试btnHTTPSendGetClick我的程序崩溃,没有异常或任何事情。任何人都可以帮我修改我的代码吗?

1 个答案:

答案 0 :(得分: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;

或者:

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;