5

With the following code, I get exception class EIdHTTPProtocolException with message 'HTTP/1.1 403 Forbidden'. Process 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;
Johan
  • 74,508
  • 24
  • 191
  • 319
Sergei Shardiko
  • 115
  • 1
  • 3
  • 9
  • 2
    It's kind of lucky, otherwise TIdHTTP would leak. – Sertac Akyuz Jun 03 '12 at 13:34
  • 2
    You're setting the `Host` property to something that obviously isn't a host name. It's not supposed to be an entire URL. You're connecting to *automation.whatismyip.com*, so use that for the `Host` property, too. – Rob Kennedy Jun 03 '12 at 22:01
  • 2
    You are not even supposed to be assigning the `Request.Host` maually at all. `TIdHTTP` manages that value internally. – Remy Lebeau Jun 04 '12 at 23:30

1 Answers1

16

You need to set your user agent, this is documented in WhatIsMyIP faq:

•Please set your program's user agent to Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 , this will keep your program from being blocked by CloudFlare

Also freeing the TIdHTTP instance should be unconditional, you're only freeing it when an exception is thrown. Use exception handling, well, to handle exceptions.

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;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • I got the same problem after your Solution the new error is 503 Service temporaly unaivable... How to fixx? – Hidden Aug 28 '13 at 21:44
  • @Poly - I don't know but they may have changed their rules. Visit [this link](http://www.whatismyip.com/ip-faq/automation-rules/) which links to [this one](http://www.whatismyip.com/membership-options/). Maybe they require an account.. – Sertac Akyuz Aug 28 '13 at 22:15
  • Thanks for the solution. I keep forgetting that I have to do this when I use Indy's get function(). Bookmarked it this time. – TheSteven Apr 07 '14 at 22:24