在Delphi

时间:2017-07-24 13:00:35

标签: delphi network-programming

我正在尝试与Web中继(连接到以太网的中继)进行通信。中继的地址是192.168.1.153端口80.我需要发送HTTP GET请求以了解状态:

GET /state.xml HTTP/1.1
Authorization: Basic bm9uZTp3ZWJyZWxheQ==

我写了这段代码:

var
  get_url, Reponse: string;
  resp: TStringStream;
  IdHTTP: TIdHTTP;
  CR, LF: char;
begin
  CR := chr(13);
  LF := chr(10);
  IdHTTP := TIdHTTP.Create();
  resp := TStringStream.Create;
  IdHTTP.Request.Host := '192.168.1.153:80';
  IdHTTP.Request.Username := 'admin'; // User
  IdHTTP.Request.Password := 'webrelay'; // Password
  IdHTTP.Request.BasicAuthentication := false; //Auth. BASIC
  try
    get_url := 'GET /state.xml HTTP/1.1' + CR + LF +
      'Authorization: Basic bm9uZTp3ZWJyZWxheQ==' + CR + LF + CR + LF;
    memoGET.Text := IdHTTP.Get(get_url);

我在IdHTTP.Get()时出错,因为端口号似乎未知。我试图写IdHTTP.Request.Port:=80但它不起作用。

更新:不幸的是,我仍然无法使用TIdHTTP。我收到这个错误:

  

项目Testeur_Webrelay.exe引发了异常类EIdHTTPProtocolException,消息为'<?xml version =“1.0”encoding =“utf-8”?>'。

我有一个有效的例子,用VB编写,但我无法将其翻译成Delphi,因为VB对我来说就像是一个外来语言:

'Connect to webrelay
port = Convert.ToInt32(portTextBox.Text)
tcpClient.Connect(addressTextBox.Text.ToString(), port)

If tcpClient.Connected Then

  'Create a network stream object
  Dim netStream As NetworkStream = tcpClient.GetStream()

  'If we can read and write to the stream then do so
  If netStream.CanWrite And netStream.CanRead Then

    'Send the on command to webrelay
    Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("GET /state.xml?noReply=0 HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
    netStream.Write(sendBytes, 0, sendBytes.Length)

    'Get the response from webrelay
    Dim bytes(tcpClient.ReceiveBufferSize) As Byte
    netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

    'Parse the response and update the webrelay state and input text boxes
    Dim returndata As String = Encoding.ASCII.GetString(bytes)

'bm9uZTp3ZWJyZWxheQ =='的确适用于'none:webrelay'而不是admin:webrelay'。

1 个答案:

答案 0 :(得分:0)

您正在以错误的方式使用TIdHTTP。改为使用它:

var
  IdHTTP: TIdHTTP;
begin
  IdHTTP := TIdHTTP.Create;
  try
    // the username encoded in 'bm9uZTp3ZWJyZWxheQ==' is 'none' instead of 'admin'... 
    IdHTTP.Request.Username := 'none'; //'admin'; // User
    IdHTTP.Request.Password := 'webrelay'; // Password
    IdHTTP.Request.BasicAuthentication := true; //Auth. BASIC
    memoGET.Text := IdHTTP.Get('http://192.168.1.153/state.xml');
  finally
    IdHTTP.Free;
  end;
end;