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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__简言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值