// Create a 'WebRequest' object with the specified url. 
 WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");  // Send the 'WebRequest' and wait for response.
WebResponse myWebResponse = myWebRequest.GetResponse();  // Obtain a 'Stream' object associated with the response object.
Stream ReceiveStream = myWebResponse.GetResponseStream();
        
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");        // Pipe the stream to a higher level stream reader with the required encoding format. 
 StreamReader readStream = new StreamReader( ReceiveStream, encode );
 Console.WriteLine("\nResponse stream received");
 Char[] read = new Char[256];        // Read 256 charcters at a time.    
 int count = readStream.Read( read, 0, 256 );
        Console.WriteLine("HTML...\r\n"); while (count > 0) 
{
         // Dump the 256 characters on a string and display the string onto the console.
    String str = new String(read, 0, count);
    Console.Write(str);
    count = readStream.Read(read, 0, 256);
}       Console.WriteLine("");
     // Release the resources of stream object.
     readStream.Close();     // Release the resources of response object.
     myWebResponse.Close(); 

解决方案 »

  1.   

    创建一个WEB请求,将请求返回的页面以UTF-8字符串打印出来
      

  2.   

    //根据url创建一个Http请求对象
    WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");
    //发送http请求,得到http响应
    WebResponse myWebResponse = myWebRequest.GetResponse();
    //从http响应对象中获取响应流
    Stream ReceiveStream = myWebResponse.GetResponseStream();
    //指定字节序列到字符的转换规则:用utf-8编码方案
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    //根据转换规则、流对象,初始化流阅读器
    StreamReader readStream = new StreamReader(ReceiveStream, encode);
    //命令行输出一行文字:收到响应流
    Console.WriteLine("\nResponse stream received");
    //声明一个char型数组
    Char[] read = new Char[256];
    //用流阅读器读取前256个字符,放入字符数组read中
    int count = readStream.Read(read, 0, 256);
    //命令行输出一行文字
    Console.WriteLine("HTML...\r\n");
    //反复进行:命令行输出字符数组read的内容,并往下再读取256个字符,知道没有字符可读取为止
    while (count > 0)
    {
    String str = new String(read, 0, count);
    Console.Write(str);
    count = readStream.Read(read, 0, 256);
    }
    Console.WriteLine("");
    //关闭流阅读器及其对应的流
    readStream.Close();
    //关闭http响应对象占用的资源
    myWebResponse.Close();