使用以下代码,我得到异常类EIdHTTPProtocolException,消息'HTTP / 1.1 403 Forbidden'。处理svchostip.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;
答案 0 :(得分:15)
您需要设置用户代理,这在WhatIsMyIP faq中有记录:
•请将程序的用户代理设置为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;