delphi - Indy 在不处理 302 的情况下获取响应文本

标签 delphi http indy

    FHTTP.HandleRedirects := False;
    try

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

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

    (Status-Line):HTTP/1.1 302 Found
    Cache-Control:no-cache, no-store
    Content-Length:148291
    Content-Type:text/html; charset=utf-8
    Date:Sun, 21 Sep 2014 09:13:49 GMT
    Expires:-1
    Location:/di
    Pragma:no-cache

In response :

<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">
...

我怎么收不到这段文字?

最佳答案

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>

关于delphi - Indy 在不处理 302 的情况下获取响应文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25957871/

相关文章:

delphi - 如何从TVirtualStringTree中删除所有节点?

java - 如何配置 apache httpcore 4 以使用代理?

http - 用于 Linux 的 TCPMon 等任何工具都可以随时随地编辑消息

Delphi - OnKeyPress 在 TStringGrid 用新字符更新单元格之前发生

delphi - Chromium:如何获取加载页面的所有形式

delphi - 不能在多个 twebbrowser 中按 Enter

web-services - 使用 HTTP PUT,但不完全替换实体

delphi - idhttp:特定站点上的 SSLv3_READ_BYTES 错误

delphi - idHttp Get + Delphi + 请求的URL被拒绝

delphi - 将 TIDCookieManager 中的 Cookie 保存到文件中