c# 访问网页简单 sample

记下来备用。

HttpWebRequest 同步调用

UriBuilder uri = new UriBuilder("http://www.cnblogs.com/xiaokang088/rss.aspx");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.Uri);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            var str = reader.ReadToEnd();


HttpWebRequest 异步调用

 public MainWindow()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            UriBuilder uri = new UriBuilder("http://www.cnblogs.com/xiaokang088/rss.aspx");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.Uri);
            request.BeginGetResponse(new AsyncCallback(handleResponce), request);
        }

        private void handleResponce(IAsyncResult ar)
        {
            HttpWebRequest request = ar.AsyncState as HttpWebRequest;
            var reponse = request.EndGetResponse(ar) as HttpWebResponse;

            var stream = reponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string str = reader.ReadToEnd();
        }

WebClient ,最简单,注意编码,否则会乱码

  WebClient client = new WebClient();
            //client.Encoding = Encoding.UTF8;
            var address = "http://www.cnblogs.com/xiaokang088/rss.aspx";
            string content = client.DownloadString(address);

 

完毕!

posted @ 2012-06-08 10:02  xiaokang088  阅读(5583)  评论(0编辑  收藏  举报