using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.Timers;

using System.Net;

using System.IO;

 

 

namespace DemoWPFUrlRequest

{

    /// <summary>

    /// Interaction logic for Window1.xaml

    /// </summary>

    public partial class Window1 : Window

    {

      

        public static string myUrl = "http://www.yahoo.com.tw";    //要抓取的網頁

 

        public Window1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            string data = getContent(myUrl);

            Console.WriteLine("data:"+data);

          

        }

 

     

 

        private string getContent(string Url)

        {

            string strResult = "";

            try

            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

                //聲明一個HttpWebRequest請求 

                request.Timeout = 30000;

                //設置連接逾時時間 

                request.Headers.Set("Pragma", "no-cache");

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream streamReceive = response.GetResponseStream();

                Encoding encoding = Encoding.GetEncoding("BIG5");

                StreamReader streamReader = new StreamReader(streamReceive, encoding);

                strResult = streamReader.ReadToEnd();

                streamReader.Close();

            }

            catch

            {

                throw;

            }

            return strResult;

        } 

    }

}

 

狼翔月影 發表在 痞客邦 PIXNET 留言(0) 人氣()