Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
23.7k views
in Technique[技术] by (71.8m points)

delphi - Why do I get "403 Forbidden" when I connect to whatismyip.com?

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...