使用以下代码,我得到异常类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;
Run Code Online (Sandbox Code Playgroud)
Ser*_*yuz 15
您需要设置用户代理,这在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;
Run Code Online (Sandbox Code Playgroud)