调用外部网站时 HttpWebRequest 无响应 API

HttpWebRequest No Response when calling an external website API

我正在尝试通过 C# 代码使用 an API that helps detect bad IP

这是文档。

How to call the API?

API requests are sent in a specific form. The API key is sent directly to the URL, as is the IP address from which you want to retrieve the information. This is the form of the URL called.

https://api.ipwarner.com/API-KEY/IP

据此写了一个函数:

private static string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse) request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream ?? throw new InvalidOperationException());
    return reader.ReadToEnd();
}

并调用它:

string myresult = Get("https://api.ipwarner.com/myapikey/myip");

然而,它卡在了 HttpWebResponse。一点反应都没有。

(我确认我的API密钥可用并且输入的IP是正确的)

怎么错了?

请设置超时并尝试。现在,您将收到错误消息。处理错误。

private static string Get(string uri)
 {
   string returnStr  = trsing.Empty;
  try
   {    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Timeout=10;
    HttpWebResponse response = (HttpWebResponse) request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream ?? throw new 
    InvalidOperationException());
    returnStr  = reader.ReadToEnd();
 }
 catch( Exception ex)
 {
  Debug.Writeline( ex.ToString());
 }

 return returnStr  ;
}

这不是你的问题,我已经检查过了,api 已关闭

你也可以检查

https://www.isitdownrightnow.com/api.ipwarner.com.html

我注册了网站并亲自测试了 api 网站已关闭

联系支持人员