delphi 测试Http服务'http://localhost:21012/'的可用性

7eumitmz  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(132)

一些XmlRpc服务器可能是由一个Web应用程序安装的,我正在搜索以测试相应服务的可用性。
Windows 10、 Delphi 11、Indy 10.6

Var
  WplHTTP: TIdHTTP;
  RequestBody: TStringStream;
  XmlReqst:string ;
begin
 //The XML-RPC endpoint for Web Profile requests is at the root of that server,
 // so that web clients can access it by POSTing to the URL “http://localhost:21012/”.
   result:=false;
   try
        XmlReqst:=C_xmlFrame;    // dummy request pour test
        RequestBody := TStringStream.create(XmlReqst);         //ok
        wplHTTP:=TidHTTP.Create;
        wplhTTP.HTTPOptions := wplHTTP.HTTPOptions + [hoNoProtocolErrorException]+[hoWantProtocolErrorContent];
        wplHTTP.Request.Accept := 'application/xml';
        wplHTTP.Request.ContentType := 'application/xml';
            try
              responseBody := wplHTTP.Post('http://localhost:21012/', RequestBody);
            except
              on E:EIdHTTPProtocolException do
              begin
                WriteLn(E.Message);
                WriteLn(E.ErrorMessage);
                result := false;
              end;
            end;
            Response := responseBody;
            if response <> ''  then   result :=  true;
          finally
            requestbody.Free;
            wplHTTP.Destroy;
       end;

我选择测试发布一个示例请求,但似乎我没有办法在缺席的情况下测试返回{AERR=10061} [如果服务启动,则工作正常]。
IdStack模块将显示以下行:

raise EIdSocketError.CreateError(AErr, WSTranslateSocketErrorMsg(AErr));

如何继续?

r7xajy2e

r7xajy2e1#

您明确要求TIdHTTP不要引发EIdHTTPProtocolException(这很好),但您试图只捕获它(为什么?),然后你想知道为什么你会得到其他你没有捕捉到的异常?
您引用的代码行字面上告诉您正在引发的异常类型(EIdSocketError),因此只需在您的except块中捕获该类型的异常 * 而不是 * EIdHTTPProtocolException,例如:

try
  ...
except
  on E: EIdSocketError do
  begin
    WriteLn(E.Message);
    WriteLn('Error Code: ' + IntToStr(E.LastError));
    Result := false;
  end;
end;

不过,我建议你把你的代码重新构造成这样:

var
  WplHTTP: TIdHTTP;
  RequestBody: TStringStream;
  XmlReqst: string;
begin
  Result := False;
  XmlReqst := C_xmlFrame;
  RequestBody := TStringStream.Create(XmlReqst);
  try
    wplHTTP := TIdHTTP.Create;
    try
      wplhTTP.HTTPOptions := wplHTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent];
      wplHTTP.Request.Accept := 'application/xml';
      wplHTTP.Request.ContentType := 'application/xml';
      try
        Response := wplHTTP.Post('http://localhost:21012/', RequestBody);
      except
        on E: Exception do
        begin
          WriteLn(E.Message);
          if E is EIdSocketError then
            WriteLn('Error Code: ' + IntToStr(EIdSocketError(E).LastError));
          Exit;
        end;
      end;
      Result := Response <> '';
    finally
      wplHTTP.Free;
    end;
  finally
    RequestBody.Free;
  end;
end;

相关问题