[英]Using HttpWebRequest and HttpWebResponse throws an error, however only on certain websites
This function checks if a url
is for a valid address, and works with http://www.google.com 此函数检查
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;
}
}
This Code is called when a menu item is clicked and is meant to update a cards price. 单击菜单项时将调用此代码,用于更新卡的价格。 It is within a
foreach
loop where the variable c
is of a custom class MagicCard
. 它在
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;
}
an example of a final url is this Although this is a valid address, it is detected as not and any other card would produce similar url's which also do not work. 最终URL的示例是此地址,尽管这是一个有效地址,但它被检测为无效,并且任何其他卡都会产生类似的URL,这些URL也不起作用。 Why is this the case?
为什么会这样呢?
Your site requires a User-Agent
. 您的站点需要一个
User-Agent
。 I Added this line 我添加了这一行
request.UserAgent = "SO/1.0";
to your code and it worked.... 到您的代码,并且有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.