C# POST方式下载Excel或文件

   HttpWebRequest request = null;
            string url = "http://lotus.chinab2bi.com/lotus/sellCsgnsaQry/exportAllDetail.hlt";   //登录页面
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            request.Accept = "text/html, application/xhtml+xml, */*";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36";
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = true;
            request.Headers.Add("Content-Disposition: attachment;filename=20190608170107.xls");
            request.CookieContainer  = cookies;
            request.KeepAlive = true;
            request.Referer = " http://lotus.chinab2bi.com/lotus/sellCsgnsaQry/query.hlt";
            // area=5&checkstr=ts6h9&image.x=0&image.y=0&passwd=167167&userid=rt67690
            //    string postData = string.Format("username={0}&password={1}&Validate={2}&isautologin=1&Submit=", txtUserName.Text, txtPassword.Text, txtValidate.Text);  //这里按照前面FireBug中查到的POST字符串做相应修改。
            string postData = string.Format("pageDetail.pageSize=10000&vendorId=30039743&siteId=&departmentId=&startdate=2019-06-01&enddate=2019-06-08&saleDateDay=&buytaxno=&menuid=822&saleDateType=day&week=", txtUserName.Text, txtPassword.Text, txtValidate.Text);
            byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = postdatabyte.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postdatabyte, 0, postdatabyte.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string strWebData = string.Empty;
            Stream responseStream = response.GetResponseStream();
            //using ()
            //{
            //    strWebData = reader.Read;
            //}


            //创建本地文件写入流
            Stream stream1 = new FileStream("C:\\123.xls", FileMode.Create);

            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream1.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream1.Close();
            responseStream.Close();

你可能感兴趣的:(C#,C#,POST,下载Excel,文件)