本文介绍了为什么我得到“403 Forbidden”当我连接到whatismyip.com?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,我收到异常类EIdHTTPProtocolException,消息为HTTP / 1.1 403 Forbidden。处理svchostip.exe(11172)

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;


推荐答案

您需要设置您的用户代理,在WhatIsMyIP :

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

同时释放 TIdHTTP 实例应该是无条件的,你当抛出异常时,它只会释放它。使用异常处理,好处处理异常。

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;

这篇关于为什么我得到“403 Forbidden”当我连接到whatismyip.com?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:09