我的目的是 get 一个 https 的网页,该网页有跳转(302)。
如果使用 HandleRedirects := True; 的方式,idhttp 会无法跳转,报内存错误:access xxx at address 0x00000004;这是 idhttp 的内部问题,我不想去调试 VCL,于是打算自己做个跳转;但我在获取跳转后的 url 并 get,通过抓包可以清楚的看到网页数据已成功返回,但 idhttp 却报 Connection Closed Gracefully 错误,并且 get 回的数据也是空字符串。代码如下:
TFakeHTTP = class(TIdHTTP)
  protected
    procedure DoRequest(const AMethod: TIdHTTPMethod; AURL: string; ASource, AResponseContent: TStream; AIgnoreReplies: array of SmallInt); override;
  end;procedure TFakeHTTP.DoRequest(const AMethod: TIdHTTPMethod; AURL: string; ASource, AResponseContent: TStream; AIgnoreReplies: array of SmallInt);
begin
    try
      inherited DoRequest(AMethod, AURL, ASource, AResponseContent, AIgnoreReplies);
    except
      on E: Exception do begin
        if (Pos('HTTP/1.1 302', E.Message) > 0) then begin
          DoRequest(AMethod, Response.Location, ASource, AResponseContent, AIgnoreReplies);
          Exit;
        end;        raise;
      end;
    end;
end;procedure TForm1.Button1Click(Sender: TObject);
var httpMain: TFakeHttp;
    sslMain: TIdSSLIOHandlerSocketOpenSSL;
begin
  httpMain := TFakeHttp.Create(nil);
  sslMain := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  try
    sslMain.SSLOptions.Method := sslvSSLv3;
    sslMain.SSLOptions.Mode := sslmUnassigned;
    httpMain.AllowCookies := True;
    httpMain.HandleRedirects := False;
    httpMain.HTTPOptions := [hoKeepOrigProtocol, hoForceEncodeParams];
    httpMain.IOHandler := sslMain;    httpMain.Request.CustomHeaders.Clear;
    httpMain.Request.Referer := '';
    httpMain.Request.Accept := '*/*';
    httpMain.Request.AcceptEncoding := 'gzip, deflate';
    httpMain.Request.Connection := 'Keep-Alive';
    httpMain.Request.AcceptLanguage := 'zh-cn';
    httpMain.Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
    httpMain.Request.Host := 'id.apple.com';
    Application.MessageBox(PAnsiChar(httpMain.Get('https://id.apple.com/cgi-bin/verify.cgi?language=US-EN&key=ZmQ0OThiY2IxNDM3NDllZjlmZmQxODAxMjNmZjk3ZWE1Y2U3M2E3ZThmNGE5MmE0MzA2ZDU3NWY5MWE1ODdjM2YzNGViYzMzY2NjNmUxZTQyYjhjYWI3MDFkNTRlZDAxYzcyODRhYjU5ZTIxMDBjNzQ5NzY2ZDQzMzQ2YjFiOGZiNzMxMzE3YWUxMjM3OTM1YjJiNDdlZmE2ODY1MjU5NzZiN2U3YTY4YTE3NzFlYmE3YmZiM2I4MzczODlkY2Qy'), ''); // 该处 url 会跳转
  finally
    httpMain.Free;
    sslMain.Free;
  end;
end;