c# 判断URL是否有用
时间:2011-01-19 来源:笨笨在成长
//判断url对应的商品是否存在,存在返回真,不存在返回假
public bool getUrlTorF(string linkUrl, string errUrl, long leng, string neiRong)
{
bool justInfo = false;
req = (HttpWebRequest)WebRequest.Create(linkUrl);
req.Method = "GET";
req.AllowAutoRedirect = false;
try
{
myResp = (HttpWebResponse)req.GetResponse();
if (leng != 0)
{
//根据内容大小来判断该商品是否有效
long content = myResp.ContentLength;
if (content < leng)
{
justInfo = true;
}
}
else
{
//根据跳转页面来判断该商品是否有效
if (myResp.StatusCode == HttpStatusCode.Redirect)
{
string redirectUrl = myResp.GetResponseHeader("Location").ToLower();
if (redirectUrl == errUrl.ToLower())
{
justInfo = true;
}
}
//根据内容关键字来判断该商品是否有效
else
{
Stream mystream = (Stream)req.GetResponse().GetResponseStream();
StreamReader mr = new StreamReader(mystream, Encoding.GetEncoding("gb2312"));
if (mr.ReadToEnd().IndexOf(neiRong) >= 0 && neiRong.Trim() != "")
{
justInfo = true;
//Console.WriteLine("找到");
}
else if (new StreamReader(mystream, Encoding.GetEncoding("utf-8")).ReadToEnd().IndexOf(neiRong) >= 0 && neiRong.Trim() != "")
{
justInfo = true;
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
justInfo = true;
// Console.WriteLine(linkUrl);
}
return justInfo;
}