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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM