• 读取HttpWebResponse流的两种方法及注意的问题


    1.  获取流

         HttpWebRequest request= (HttpWebRequest)WebRequest.Create(uri); //构建http request
         
    request.Method = "get";
         HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();    //发出请求并获得Response
         resStream = response.GetResponseStream();          //获得Response的流

    2. 读
    1).  第一种方式:
         
     int count = (int)response.ContentLength;
                    int offset = 0;
                    buf = new byte[count];
                    while (count > 0)
                    {
                        int n = resStream.Read(buf,offset,count);
                        if (n == 0) break;
                        count -= n;
                        offset += n;
                        Console.WriteLine( "in loop " + getString(buf) ); //测试循环次数
                    }
         string content = Encoding.Default.GetString(buf, 0, buf.Length);

         必须循环读流, 不能一次读(resStream.Read(buf,0,count); ), 否则读的流可能不完整

    2) 第二种方式://用StreamReader读取流
         string content = "";

         using (StreamReader  sr = new StreamReader(resStream))     
         {
              content = sr.ReadToEnd();
         }

  • 相关阅读:
    ARPG手游实战练习(八)
    ARPG手游实战练习(七)
    ARPG手游实战练习(六)
    ARPG手游实战练习(五)
    ARPG手游实战练习(四)
    ARPG手游实战练习(三)
    C# Array类的Sort()方法
    C#继承讲解以及对象的创建
    单例模式
    愤怒的小鸟(练习版)
  • 原文地址:https://www.cnblogs.com/Herzog3/p/6133445.html
Copyright © 2020-2023  润新知