获取Bing每日一图作为登陆背景图片
之前使用 幻杀博客提供的必应每日图片API作为网站后台登陆页面的背景图片,一直都很稳定,但今天一大早过来 发现获取不到背景图片了,去到幻杀博客看到挂上了一个公告,因为流量使用的问题,到下月为止API使用不了。这一下,我就懵逼了,之前想偷下懒,反正也在开发阶段,没必要自己写,现在API使用不了了,咋办?没办法只有自己写了。
整理下思路:进入登陆界面时,判断下是否有存在今天的图片;如果存在直接返回今天的图片地址给前台;不存在 则异步去下载当天图片,同时向前推十天,一天天检查是否存在图片,存在就立刻返回此图片路径,都没有就返回默认图片路径。
1 private string GetWallpaper() 2 { 3 string wallPath = System.Web.Hosting.HostingEnvironment.MapPath("~/") + "wallpaper\\"; 4 string wall = "/wallpaper/20160715.jpg"; 5 string temp = wallPath + DateTime.Now.ToString("yyyyMMdd") + ".jpg"; 6 if (System.IO.File.Exists(temp)) 7 { 8 wall = "/wallpaper/" + DateTime.Now.ToString("yyyyMMdd") + ".jpg"; 9 } 10 else 11 { 12 //异步开始下载bing图片 13 TaskDelegat downloadWall = Task; 14 IAsyncResult asyncResult = downloadWall.BeginInvoke(temp, null, null); 15 asyncResult.AsyncWaitHandle.WaitOne(0); 16 17 for (int i = 1; i <= 11; i++) 18 { 19 temp = wallPath + DateTime.Now.AddDays(0 - i).ToString("yyyyMMdd") + ".jpg"; 20 if (System.IO.File.Exists(temp)) 21 { 22 wall = "/wallpaper/" + DateTime.Now.AddDays(0 - i).ToString("yyyyMMdd") + ".jpg"; 23 break; 24 } 25 } 26 } 27 return wall; 28 }
1 private delegate void TaskDelegat(string path); 2 private static void Task(string path) 3 { 4 try { 5 string json = string.Empty; 6 //请求bing壁纸链接 7 using (var webclient = new WebClient()) 8 { 9 json = webclient.DownloadString("http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"); 10 } 11 Regex urlreg = new Regex(@"http://.*?.jpg"); 12 string url = ""; 13 foreach (Match mch in urlreg.Matches(json)) 14 { 15 url = mch.Value.Trim(); 16 } 17 if (!string.IsNullOrEmpty(url)) 18 { 19 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 20 req.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; 21 req.Headers.Add("Accept-Encoding", "gzip"); 22 WebResponse res = req.GetResponse(); 23 Stream resStream = res.GetResponseStream(); 24 int count = (int)res.ContentLength; 25 int offset = 0; 26 byte[] buf = new byte[count]; 27 while (count > 0) 28 { 29 int n = resStream.Read(buf, offset, count); 30 if (n == 0) break; 31 count -= n; 32 offset += n; 33 } 34 FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); 35 fs.Write(buf, 0, buf.Length); 36 fs.Flush(); 37 fs.Close(); 38 } 39 } 40 catch(Exception ex) 41 { 42 throw ex; 43 } 44 }