You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi+Indy环境下捕获XML-RPC服务不可达的AERR=10061错误?

测试XML-RPC服务可用性的异常处理问题

问题

环境:Windows 10、Delphi 11、Indy 10.6
需求:通过TIdHTTP发送POST请求,测试Web应用的XML-RPC服务可用性。

测试代码如下:

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

解决方法

  • 捕获对应底层异常:EIdSocketError是Indy的底层网络异常,不属于EIdHTTPProtocolException的捕获范围,需要单独添加捕获分支,同时可以加上兜底捕获覆盖其他异常:
    try
      responseBody := wplHTTP.Post('http://localhost:21012/', RequestBody);
    except
      on E: EIdHTTPProtocolException do
      begin
        WriteLn(E.Message);
        WriteLn(E.ErrorMessage);
        result := false;
      end;
      on E: EIdSocketError do
      begin
        WriteLn('网络连接错误:' + E.Message);
        result := false;
      end;
      on E: EIdException do
      begin
        WriteLn('Indy组件错误:' + E.Message);
        result := false;
      end;
      on E: Exception do
      begin
        WriteLn('其他错误:' + E.Message);
        result := false;
      end;
    end;
    
  • 优化逻辑分支:异常发生后直接设置result := false即可,无需在异常块外再判断响应内容——因为异常触发时不会执行到后续的响应赋值和判断代码。
  • 规范资源释放:将wplHTTP.Destroy替换为wplHTTP.Free,更符合Delphi的资源释放习惯,避免潜在的内存问题。

内容的提问来源于stack exchange,提问作者Jean-Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:51:02