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);
        }

좋은 웹페이지 즐겨찾기