• httpwebrequest抓取网页数据非字符串时要使用流直接写文件


      比如返回数据为Excel,图片等等非字符串数据。不要使用reader.ReadToEnd();字符串格式的才使用这个。
      直接存Stream为cvs或者xls。

        public static Stream HttpPost2(string url)
        {
            HttpWebResponse response = HttpPost(url);
    
            //将获取的网络流转化成内存流
            Stream stream = response.GetResponseStream();
    
            MemoryStream memoryStream = new MemoryStream();
    
            //将基础流写入内存流
            const int bufferLength = 1024;
            byte[] buffer = new byte[bufferLength];
            int actual = stream.Read(buffer, 0, bufferLength);
            while (actual > 0)
            {
                // 读、写过程中,流的位置会自动走。
                memoryStream.Write(buffer, 0, actual);
                actual = stream.Read(buffer, 0, bufferLength);
            }
            memoryStream.Position = 0;
    
            return memoryStream;
    
        }
            private static void WriteThis2(string filePath, string fileName, Stream stream)
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
    
                //把Stream转换成 byte[]
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                //设置当前流的位置为流的开始
                stream.Seek(0, SeekOrigin.Begin);
                //把byte[]写入文件
                string path = Path.Combine(filePath, fileName);
                FileStream fs = new FileStream(path, FileMode.Create);
    
                BinaryWriter bw = new BinaryWriter(fs);
                //开始写入
                bw.Write(bytes);
                //清空缓冲区、关闭流
                bw.Flush();
                bw.Close();
                fs.Close();
    
            }
  • 相关阅读:
    MySQL函数大全
    Hibernate的理论知识点
    捕获异常
    重定向到其他的页面
    Jquery中val、text、html的区别
    条件注释判断浏览器<!--[if !IE]><!--[if IE]><!--[if lt IE 6]><!--[if gte IE 6]>
    inline-block元素的4px空白间距解决方案
    img标签中alt属性与title属性
    3像素文本偏移bug 解决方案
    google Ip
  • 原文地址:https://www.cnblogs.com/cuihongyu3503319/p/15250605.html
Copyright © 2020-2023  润新知