[英]Using HttpWebRequest and HttpWebResponse throws an error, however only on certain websites
此函数检查url
是否为有效地址,并与http://www.google.com一起使用
public static bool CheckValidURL(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "GET";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
bool isValid;
if (response.StatusCode == HttpStatusCode.OK)
{
isValid = true;
}
else
{
isValid = false;
}
response.Close();
return isValid;
}
catch
{
//Any exception will returns false.
return false;
}
}
单击菜单项时将调用此代码,用于更新卡的价格。 它在foreach
循环中,其中变量c
是自定义类MagicCard
。
string url = "";
string webCardName = c.name.ToLower().Replace(" ", "-").Replace(",", "").Replace("\'", "");
string webSetName = MagicCard.GetSetName(c).ToLower().Replace(" ", "-").Replace(",", "").Replace("\'", "");
url = string.Format("shop.tcgplayer.com/magic/{0}/{1}", webSetName, webCardName);
if (WebScraper.CheckValidURL(url) == false)
{
MessageBox.Show("ERROR: URL = " + url);
return;
}
最终URL的示例是此地址,尽管这是一个有效地址,但它被检测为无效,并且任何其他卡都会产生类似的URL,这些URL也不起作用。 为什么会这样呢?
您的站点需要一个User-Agent
。 我添加了这一行
request.UserAgent = "SO/1.0";
到您的代码,并且有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.