想做个网址导航,收藏自己常用的网站。
准备工作:网站图标获取接口制作
思路:判断网站根目录下favicon.ico是否存在,不存在,查找favicon网页中链接地址
代码:
_ueditor_page_break_tag_
//获取网站图标 public static string getFavUrl(string Url) { string favUrl=""; Url = Url.Replace("http://", "").Replace("/",""); HttpWebRequest request = WebRequest.Create(@"http://" + Url + @"/favicon.ico") as HttpWebRequest; try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; favUrl = "http://" + Url + @"/favicon.ico"; } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { // Do something //获取页面的favicon路径 string result = HttpHandle.GetHtml(@"http://" + Url,"UTF-8"); string[] FormContent = result.Split(new string[] { "</head>" }, StringSplitOptions.RemoveEmptyEntries); if (FormContent.Length >= 1) { string pat1 = "rel=\"shortcut icon\" href=\"(.+?)"; Regex r1 = new Regex(pat1, RegexOptions.IgnoreCase); MatchCollection mc1; mc1 = r1.Matches(FormContent[0]); if (mc1.Count > 0) { favUrl = mc1[0].Value.Replace("rel=\"shortcut icon\" href=\"", ""); ; } } } else { // Do something else favUrl = "nothing"; } } } return favUrl; }
遇到的问题:
1.WebRequest 404的判断,如果文件不存在,会报错,要进行try catch处理。
资料参考:
1.httpstatuscode http://msdn.microsoft.com/zh-cn/library/system.net.httpstatuscode.aspx
2.WebRequest 404 http://stackoverflow.com/questions/1949610/how-can-i-catch-a-404
3.通过Google接口获取 http://www.btorange.com/2010/04/09/from-google-get-favicon.html
4.php制作接口 http://www.521php.com/archives/1210/
5.asp.net获取favicon http://www.cnblogs.com/TianFang/archive/2008/06/01/1211747.html