【问题标题】:Indy Get response text while not handling 302Indy 在不处理 302 时获取响应文本
【发布时间】:2014-11-15 11:05:50
【问题描述】:
    FHTTP.HandleRedirects := False;
    try

      StrPage := FHTTP.Get('https://somesite.site');
    except
    end;

有重定向 302,但我需要从此请求中获取文本.. 回应:

(状态行):找到 HTTP/1.1 302 缓存控制:无缓存,无存储 内容长度:148291 内容类型:文本/html;字符集=utf-8 日期:2014 年 9 月 21 日星期日 09:13:49 GMT 过期:-1 地点:/di 杂注:无缓存

作为回应:

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/di">here</a>.</h2>
</body></html>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
...

我怎么不能得到这个文本?

【问题讨论】:

    标签: delphi http indy


    【解决方案1】:

    HandleRedirects := False时,302状态码会导致TIdHTTP引发EIdHTTPProtocolException异常。
    可以通过EIdHTTPProtocolException.ErrorMessage 访问响应的内容。

    示例:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      StrPage: string;
    begin
      IdHttp1.HandleRedirects := False;
      try
        StrPage := IdHttp1.Get('http://www.gmail.com/');
      except
        on E: EIdHTTPProtocolException do
        begin
          if not ((E.ErrorCode = 301) or (E.ErrorCode = 302)) then raise;
          StrPage := E.ErrorMessage;
          ShowMessage(StrPage);
        end
        else
          raise;
      end;
    end;
    

    输出:

    <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
    <TITLE>301 Moved</TITLE></HEAD><BODY>
    <H1>301 Moved</H1>
    The document has moved
    <A HREF="https://mail.google.com/mail/">here</A>.
    </BODY></HTML>
    

    【讨论】:

      【解决方案2】:

      除了@kobik 的回答(技术上是准确的)之外,还有一些额外的注意事项。

      您显示的响应正文相当少,它提供的唯一真正有用的信息是人类可读的文本消息,其中包含指向被重定向到的 URL 的 HTML 链接。如果您只是对 URL 感兴趣,您可以从TIdHTTP.Response.Location 属性或TIdHTTP.OnRedirect 事件中自行获取。对于OnRedirect,您可以将其Handled 参数设置为False 以跳过实际重定向,而无需将HandleRedirets 设置为False。

      如果您不希望在 302 上引发 EIdHTTPProtocolException 异常,您可以在 TIdHTTP.HTTPOptions 属性中启用 hoNoProtocolErrorException 标志,或者直接调用 TIdHTTP.DoRequest() 并在其 AIgnoreReplies 属性中指定 302 .无论哪种方式,您都可以在请求退出后检查TIdHTTP.Response.ResponseCode 属性,而不会引发异常。但是,如果您禁用 EIdHTTPProtocolException,您将无法访问正文(TIdHTTP 将读取并丢弃它)除非您启用 hoWantProtocolErrorContent 标志。无论哪种方式,您都可以访问响应标头。

      【讨论】:

      • 我在 HTTPOptions 或 idhttp.pas 的其他任何地方都没有找到类似 hoNoProtocolErrorException 的东西? (XE2 附带 v1.65)。
      • XE2 附带 IdHTTP.pas 修订版 4682 (Indy 10.5.8)。 hoNoProtocolErrorException 在修订版 4936 中添加(Indy 10.6.0,在 XE4 中可用),hoWantProtocolErrorContent 在修订版 5321 中添加(Indy 10.6.2,在 10.1 Berlin 中可用)。如果你想在 XE2 中使用它们,你必须升级你的 Indy 安装。
      猜你喜欢
      • 1970-01-01
      • 2012-03-02
      • 2018-07-15
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 2020-05-03
      • 2015-08-31
      相关资源
      最近更新 更多