zoukankan      html  css  js  c++  java
  • 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();
    
            }
  • 相关阅读:
    使用Strust2框架写HelloWorld
    MyEclipse10搭建Strust2开发环境
    MyEclipse使用总结——在MyEclipse中设置jsp页面为默认utf-8编码
    HTML一些标签注意事项
    Spring常用注解
    VB.NET中Module的概念
    vs2008发布项目失败的解决方法
    Java开发中的一些小技巧
    DNS服务器
    关于在Struts2的Action中使用domain模型接收参数的问题
  • 原文地址:https://www.cnblogs.com/cuihongyu3503319/p/15250605.html
Copyright © 2011-2022 走看看