利用HttpWebRequest實現POST和GET方法


注:要將System.Web.DLL加入引用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Web;

namespace OJ_Temp2
{
    //模擬登入(OK!)
    class Test
    {
        /// </summary>
        /// RequestUrl: request some url, return the response.
        /// 適合方式:POST/GET
        /// </summary>
        /// <param name="strUrl">the url</param>
        /// <param name="strPostDatas">the post data</param>
        /// <param name="method">發送方式:"POST"或"GET"</param>
        /// <param name="objencoding">編碼方式("utf-8")</param>
        /// <param name="objCookieContainer">cookie's(session's) container</param>
        /// <param name="rescookie">返回string類型的cookie</param>
        /// <param name="flag">flag = false 直接發送 不分割 (默認)</param>
        /// <returns>返回HTML頁面</returns>
        public static string RequestUrl(string strUrl, string strPostDatas,string method,string objencoding, ref CookieContainer objCookieContainer,bool flag, ref string rescookie) 
        {
            HttpWebResponse res = null;
            string strResponse = "";
            //string strcookie = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
                req.Method = method;
                req.KeepAlive = true;
                req.ContentType = "application/x-www-form-urlencoded";
                //req.Timeout = 20;

                if (objCookieContainer == null)
                    objCookieContainer = new CookieContainer();
                req.CookieContainer = objCookieContainer;

                StringBuilder objEncodedPostDatas = new StringBuilder();
                byte[] postDatas = null;

                req.ContentLength = 0;
                #region SendData
                if (strPostDatas != null && strPostDatas.Length > 0)
                {
                    if (flag == true)
                    {
                        string[] datas = strPostDatas.TrimStart('?').Split(new char[] { '&' });
                        for (int i = 0; i < datas.Length; i++)
                        {
                            string[] keyValue = datas[i].Split(new char[] { '=' });
                            if (keyValue.Length >= 2)
                            {
                                objEncodedPostDatas.Append(HttpUtility.UrlEncode(keyValue[0]));
                                objEncodedPostDatas.Append("=");
                                objEncodedPostDatas.Append(HttpUtility.UrlEncode(keyValue[1]));
                                if (i < datas.Length - 1)
                                {
                                    objEncodedPostDatas.Append("&");
                                }
                            }
                        }
                        //postDatas = Encoding.UTF8.GetBytes(objEncodedPostDatas.ToString());
                        postDatas = Encoding.GetEncoding(objencoding.Trim()).GetBytes(objEncodedPostDatas.ToString());
                    }
                    else
                    {
                        //postDatas = Encoding.UTF8.GetBytes(strPostDatas);
                        postDatas = Encoding.GetEncoding(objencoding.Trim()).GetBytes(strPostDatas);
                    }

                    req.ContentLength = postDatas.Length;
                    using (Stream reqStream = req.GetRequestStream())
                    {
                        reqStream.Write(postDatas, 0, postDatas.Length);
                    }
                }
                #endregion
                res = (HttpWebResponse)req.GetResponse();
                objCookieContainer = req.CookieContainer;
                CookieCollection mycookie = objCookieContainer.GetCookies(req.RequestUri);
                foreach (Cookie cook in mycookie)
                {
                    rescookie = cook.Name + "=" + cook.Value; 
                }
                using (Stream resStream = res.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(resStream, System.Text.Encoding.GetEncoding(objencoding.Trim())))
                    {
                        strResponse = sr.ReadToEnd();
                    }
                }
            }
            //catch (Exception ex)
            //{
            //    strResponse = ex.ToString();
            //}  
            finally
            {
                if (res != null)
                {
                    res.Close();
                }
            }
            return strResponse;
        }
    }
}

模擬登入:

        public void Login()
        {
            CookieContainer mycookie = new CookieContainer();

            ///HIT_Login
            string strUrl = "http://acm.hit.edu.cn/hoj/system/login?user=nbu_virtual2&password=nbu_virtual2&submit=Login";
            string strPostdata = "user=nbu_virtual2&password=nbu_virtual2&submit=Login";

            ///HIT_Post(problem)
            string strUrl1 = "http://acm.hit.edu.cn/hoj/problem/submit?";
            string code = File.ReadAllText("code.txt");
            string strPostdata1 = "Proid=1001&Language=C%2B%2B&Source=" + HttpUtility.UrlEncode(code);

            string rescookie = "";
            string fuck_res = Test.RequestUrl(strUrl, strPostdata,"POST","utf-8", ref mycookie,false,ref rescookie);
            MessageBox.Show(rescookie);
            string fuck_res1 = Test.RequestUrl(strUrl1, strPostdata1, "POST", "utf-8", ref mycookie, false, ref rescookie);
            
            WriteText.Write_Text("fuck_res.txt", fuck_res);
            WriteText.Write_Text("fuck_res1.txt", fuck_res1);
        }


發佈了141 篇原創文章 · 獲贊 57 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章