5

使用以下代码,我得到带有消息“HTTP/1.1 403 Forbidden”的异常类 EIdHTTPProtocolException。进程 svhostip.exe (11172)

function GetInternetIP:string;
var
  IdHTTPMainUrl : TIdHTTP;
begin
  try
    IdHTTPMainUrl := TIdHTTP.Create(nil);
    IdHTTPMainUrl.Request.Host := 'http://www.whatismyip.com/automation/n09230945.asp';
    Result := idHTTPMainUrl.Get('http://automation.whatismyip.com/n09230945.asp');
  except
    IdHTTPMainUrl.Free;
  end;
end;
4

1 回答 1

16

您需要设置您的用户代理,这记录在 WhatIsMyIP常见问题解答中:

•请将您程序的用户代理设置为 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 ,这将防止您的程序被 CloudFlare 阻止

释放TIdHTTP实例也应该是无条件的,只有在引发异常时才释放它。使用异常处理,好吧,处理异常。

function GetInternetIP:string;
var
  IdHTTPMainUrl : TIdHTTP;
begin
  IdHTTPMainUrl := TIdHTTP.Create(nil);
  try
    IdHTTPMainUrl.Request.UserAgent :=
      'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0';
    Result := idHTTPMainUrl.Get('http://automation.whatismyip.com/n09230945.asp');
  finally
    IdHTTPMainUrl.Free;
  end;
end;
于 2012-06-03T14:08:19.953 回答