首页 > 代码库 > c# Http连接初探

c# Http连接初探

准备在端午节期间做一个网络爬虫。

 

using System;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var request = WebRequest.Create(@"http://www.baidu.com");
            var res = request.GetResponse();
            Stream myStream = res.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");
            StreamReader myStreamReader = new StreamReader(myStream, encode);
            string strhtml = myStreamReader.ReadToEnd();
            res.Close();
            string stroutput = strhtml;

            Console.WriteLine(stroutput);
            Console.Read();
        }
    }
}

 

用GB2312和UNICODE都是乱码。Response似乎不是异步的。下一步继续研究。