读取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();
     }

你可能感兴趣的:(response)