1 public void DownloadFile(string URL, string filename)
2 {
3 HttpWebRequest req = null;
4 HttpWebResponse rep = null;
5 Stream st = null;
6 Stream so = null;
7 try
8 {
9 req = (HttpWebRequest)WebRequest.Create(URL);//请求网络资源
10
11 req.UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36";
12
13 rep = (HttpWebResponse)req.GetResponse();//返回Internet资源的响应
14 long totalBytes = rep.ContentLength;//获取请求返回内容的长度
15 st = rep.GetResponseStream();//读取服务器的响应资源,以IO流的形式进行读写
16 so = new FileStream(filename, FileMode.Create);
17 long totalDownloadedByte = 0;
18 byte[] by = new byte[1024];
19 int osize = st.Read(by, 0, (int)by.Length);
20 while (osize > 0)
21 {
22 totalDownloadedByte = osize + totalDownloadedByte;
23 so.Write(by, 0, osize);
24 osize = st.Read(by, 0, (int)by.Length);//读取当前字节流的总长度
25 }
26 so.Flush();
27 }
28 catch (Exception ex) { ex.ToString(); }
29 finally
30 {
31 if (so != null) { so.Close(); so.Dispose(); }
32 if (st != null) { st.Close(); st.Dispose(); }
33 if (rep != null) { rep.Close(); rep.Dispose(); }
34 if (req != null) { req.Abort(); }
35
36 }
37 }