之前使用 幻殺博客提供的必應每日圖片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 }
