下载验证码等网络资源
using System.IO; using System.IO.Compression; using System.Net; namespace ConsoleApplication2 { public static class HttpFileDownloader { public static byte[] DownLoad(string url) { byte[] buffer = null; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; req.Headers.Add("Accept-Encoding", "gzip, deflate"); req.KeepAlive = true; using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { Stream reader; if (response.ContentEncoding.ToLower().Contains("gzip")) { reader = new System.IO.Compression.GZipStream(response.GetResponseStream(), CompressionMode.Decompress); } else { reader = response.GetResponseStream(); } if (reader.CanRead) { MemoryStream ms = new MemoryStream(); reader.CopyTo(ms); buffer = ms.GetBuffer(); } reader = null; } req = null; return buffer; } } }
保存到本地
static void Main(string[] args) { string url = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand" + "&rnd=" + DateTime.Now.Millisecond; byte[] buffer = HttpFileDownloader.DownLoad(url); if (buffer!=null) { System.IO.File.WriteAllBytes(@"d:\img.png", buffer); } }