利用HttpWebRequest下载资源

简介: private void DownLoadFile() { HttpWebRequest httpWebReq = (HttpWebRequest)WebRequest.
 private void DownLoadFile()
        {
            HttpWebRequest httpWebReq = (HttpWebRequest)WebRequest.Create(address);
            httpWebReq.Method = WebRequestMethods.Http.Get;
            HttpWebResponse httpWebResp = (HttpWebResponse)httpWebReq.GetResponse();
            long contentLength = httpWebResp.ContentLength;
            this.progressBar1.Maximum = int.Parse(contentLength.ToString());

            //设置临时文件名
            string tempFileName = fileName + ".tempdl";
            //string cfgFileName = fileName + ".tempdlcfg";
            FileInfo fi = new FileInfo(tempFileName);
            if (fi.Exists)
            {
                //日后断点续传[暂时不做]
                //直接删除存在
                fi.Delete();
            }
            try
            {
                //创建临时文件 
                using (FileStream fs = fi.Create())
                {
                    fs.SetLength(contentLength);
                    //获取响应流
                    using (Stream respstm = httpWebResp.GetResponseStream())
                    {
                        if (respstm.CanRead)
                        {
                            Byte[] buffer = new byte[1024];
                            //读取数据到缓冲
                            int length = respstm.Read(buffer, 0, buffer.Length);
                            //设置进度条直
                            this.SetProgressBar(length);
                            while (length > 0)
                            {
                                //将网络流写入本地
                                fs.Write(buffer, 0, length);
                                //继续读取
                                length = respstm.Read(buffer, 0, buffer.Length);

                                //断点续传配置文件
                                //using (FileStream cfgfs = new FileStream(cfgFileName, FileMode.CreateNew))
                                //{
                                //    cfgfs.Write()
                                //}

                                //设置进度条信息
                                //this.SetProgressBar(length);
                            }
                        }
                        //写配置文件
                        //FileInfo fik12cfg = new FileInfo();
                    }
                }
                //this.ReNameApp(fi, fileName);
                //this.RunAtApp(fileName);
            }
            catch
            { }
        }

目录
相关文章
|
Java 开发者
使用 Response 下载文件 | 学习笔记
快速学习使用 Response 下载文件,介绍了使用 Response 下载文件系统机制, 以及在实际应用过程中如何使用。
276 0
使用 Response 下载文件 | 学习笔记
|
域名解析 网络协议 应用服务中间件
|
JSON 数据格式
HttpRequest常见问题
1、Q:HttpRequest真机请求报错误码error:4,errorMessage:无权调用该接口,和报错误码error11 A:需要把域名添加到开放平台中的小程序httpRequest接口请求域名白名单中 2, 2、Q:真机请求中如果Android请求正常,ios不能正常请求到数据请求为...
1191 0

热门文章

最新文章