逐行返回http响应的内容

 

前言

问题:1、什么是特殊字符?

        2、为什么要处理特殊字符?

答:特殊字符指相对于传统或常用的符号外,使用频率较少字符且难以直接输入的符号,比如数学符号;单位符号;制表符等

     有些符号在URL中是不能直接传递的,如果要在URL中传递这些特殊符号,那么就要使用他们的编码了。编码的格式为:%加字符的ASCII码,即一个百分号%,后面跟对应字符的ASCII(16进制)码值。例如 空格的编码值是"%20"。

 

问题

如何逐行返回http响应的内容,而不是把整个内容作为一个字符串

设计

通过HttpWebRequest.GetResponse()方法获得http响应的数据流(Stream),并且把这个stream传给StreamReader()的构造函数,然后在一个while循环中通过StreamReader.ReadLine()方法进行逐行读取。

方案

 

 public static void stream()
 {
      Stream st = null;
      StreamReader sr = new StreamReader(st);

      string line = null;
      Console.WriteLine("HTTP Response is line-by-line:");
      while((line=sr.ReadLine())!=null)
      {
          Console.WriteLine(line);
      }
      st.Close();
      sr.Close();
            
}

 经我琢磨

       static void Main(string[] args)
        {
            stream();
        }
        public static void stream()
        {
            string url = "www.baidu.com";
            //定义一个byte数组
            byte[] array = Encoding.ASCII.GetBytes(url);
            //将数组赋给数据流
            MemoryStream stream = new MemoryStream(array);            
            StreamReader sr = new StreamReader(stream);

            //Stream st = null;
            //StreamReader sr = new StreamReader(st);

            string line = null;
            Console.WriteLine("HTTP Response is line-by-line:");
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            stream.Close();
            sr.Close();

          }

 

注解

用于发送http请求的三种基本方法(WebClient、WebReqest、HttpWebRequest)都支持通过某个方法以Stream对象的形式返回与它们相关联的http响应。

posted @ 2014-07-15 17:04  韩梦芫  阅读(464)  评论(0编辑  收藏  举报