C# HttpWebRequest實作POST來取得網頁內容

C# HttpWebRequest實作POST來取得網頁內容 | 聰明的生活2

C# HttpWebRequest實作POST來取得網頁內容

 

程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace yslifes
{
    class WebModule
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(WebModule));
        //回傳的網頁內容
        private StringBuilder buff;
        //記錄Session及Cookie,如果登入時Session將一直存在
        private static CookieContainer cookie = null;
        public WebModule()
        {
            buff = new StringBuilder();
            cookie = new CookieContainer();

        }
        //取得網頁內容
        public string getContent()
        {
            return buff.ToString();
        }
        //做post事件
        public bool doPost(string sUrl, string data, string referer)
        {
            bool dosuccess = false;
            HttpWebRequest URLConn = null;
            try
            {
                //URL連線
                URLConn = (HttpWebRequest)WebRequest.Create(sUrl);
                //連線最大等待時間
                URLConn.Timeout = 10000;
                URLConn.Method = "POST";
                //設定Header模擬瀏覽器
                URLConn.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) "
                          + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)";
                URLConn.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                URLConn.Headers.Set("Accept-Language",
                    "zh-tw,en-us;q=0.7,en;q=0.3");
                URLConn.Headers.Set("Accept-Charse",
                    "Big5,utf-8;q=0.7,*;q=0.7");
                //設定referer
                if (referer != null)
                {

                    URLConn.Referer = referer;
                }
                //純文字傳送,使用application/x-www-form-urlencoded
                //如需傳送檔案,則需用multipart/form-data
                URLConn.ContentType = "application/x-www-form-urlencoded";
                //自動從導
                URLConn.AllowAutoRedirect = true;

                if (data == null)
                    data = "";
                logger.Debug(data);
                //把要傳送的資料變成binary
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                URLConn.ContentLength = bytes.Length;

                //設定Cookie,Session
                URLConn.CookieContainer = cookie;

                //送出post資料
                if (data.Length > 0)
                {
                    Stream oStreamOut = URLConn.GetRequestStream();
                    oStreamOut.Write(bytes, 0, bytes.Length);
                    //oStreamOut.Close();
                }

                //取回回傳內容
                string html = (new StreamReader(URLConn.GetResponse().GetResponseStream())).ReadToEnd();
                buff.Clear();
                buff.Append(html);

                dosuccess = true;
            }
            catch (Exception ex)
            {
                logger.Info(ex.StackTrace);

            }
            finally
            {
                try
                {
                    if (URLConn != null)
                    {
                        URLConn.GetResponse().Close();
                        URLConn.GetRequestStream().Close();
                    }
                }
                catch (Exception exx)
                {
                    logger.Debug(exx.StackTrace);

                }
            }

            return dosuccess;

        }
    }

    class Program
    {

        static void Main(string[] args)
        {

            System.IO.FileInfo f = new System.IO.FileInfo("log4net.config");
            log4net.Config.XmlConfigurator.Configure(f);

            ILog logger = LogManager.GetLogger(typeof(Program));

            WebModule module = new WebModule();
            module.doPost("http://localhost:8080/test/MyData.jsp", "test=123", null);
            Console.WriteLine("解答:"+module.getContent());

            module.doPost("http://localhost:8080/test/MyData.jsp", "test=456", null);
            Console.WriteLine("解答:" + module.getContent());
            Console.ReadLine();

        }
    }
}

log4net的使用可以參考Log4net Visual Studio版的log4j

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 5 + 11 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)