.net模拟登录博客园,使用httpWebRequest登录并发布随笔文章

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace TestHttpWebRequest
{
    class Program
    {
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string A_0, string A_1, string A_2);
        /// <summary>
        /// 下一次请求的Url
        /// </summary>
        public static string NextRequestUrl
        {
            get;
            set;
        }

        /// <summary>
        /// 若要从远程调用中获取COOKIE一定要为request设定一个CookieContainer用来装载返回的cookies
        /// </summary>
        public static CookieContainer CookieContainer
        {
            get;
            set;
        }

        /// <summary>
        /// Cookies 字符创
        /// </summary>
        public static string CookiesString
        {
            get;
            set;
        }

        static void Main(string[] args)
        {
            // 博客园首页地址
            string uri = "http://passport.cnblogs.com/login.aspx?ReturnUrl=http%3a%2f%2fwww.cnblogs.com%2f";

            
            StringBuilder dataBuilder = new StringBuilder();

            dataBuilder.Append("__EVENTARGUMENT=");
            dataBuilder.Append("&__EVENTTARGET=");
            dataBuilder.Append("&__EVENTVALIDATION=");
            dataBuilder.Append("%2FwEdAAUyDI6H%2Fs9f%2BZALqNAA4PyUhI6Xi65hwcQ8%2FQoQCF8JIahXufbhIqPmwKf992GTkd0wq1PKp6%2B%2F1yNGng6H71Uxop4oRunf14dz2Zt2%2BQKDEIYpifFQj3yQiLk3eeHVQqcjiaAP");
            dataBuilder.Append("&__VIEWSTATE=");
            dataBuilder.Append("%2FwEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt");
            dataBuilder.Append("&btnLogin=");
            dataBuilder.Append("%E7%99%BB++%E5%BD%95");
            dataBuilder.Append("&tbPassword=");
            dataBuilder.Append("password");
            dataBuilder.Append("&tbUserName=");
            dataBuilder.Append("account");
            dataBuilder.Append("&txtReturnUrl=");
            dataBuilder.Append("http%3A%2F%2Fwww.cnblogs.com%2F");
            string data = dataBuilder.ToString();
            string responstr = GetResponse(uri, "POST", data, "http://passport.cnblogs.com/login.aspx?ReturnUrl=http%3A%2F%2Fwww.cnblogs.com%2F",true);
            //GetPage();
            //GetPage(true);
            //GetPage();

            string uri2 = "http://i.cnblogs.com/EditPosts.aspx?opt=1";

            string srcString = GetPage(uri2);

            //Get the ViewState
            string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
            int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
            int j = srcString.IndexOf("\"", i);
            string viewState = srcString.Substring(i, j - i);

            dataBuilder.Clear();
            dataBuilder.Append("__VIEWSTATE=");
            dataBuilder.Append(System.Web.HttpUtility.UrlEncode(viewState));
            dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$txbTitle") + "=");//文章标题
            dataBuilder.Append(System.Web.HttpUtility.UrlEncode("test111212121"));
            dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$txbEntryName") + "=");
            dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$EditorBody") + "=");//文章内容
            dataBuilder.Append(System.Web.HttpUtility.UrlEncode("<p>22222222333333333</p>"));
            //dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$chkDisplayHomePage") + "=");
            //dataBuilder.Append(System.Web.HttpUtility.UrlEncode("on"));
            //dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$chkMainSyndication") + "=");
            //dataBuilder.Append(System.Web.HttpUtility.UrlEncode("on"));
            dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$ckbPublished") + "=");
            dataBuilder.Append(System.Web.HttpUtility.UrlEncode("on"));//这个开启是发布状态,不开启则是未发布
            //dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$chkComments") + "=");
            //dataBuilder.Append(System.Web.HttpUtility.UrlEncode("on"));
            //dataBuilder.Append("&Editor%24Edit%24Advanced%24tbEnryPassword=");
            //dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$txbEntryName") + "=");
            //dataBuilder.Append("&" + System.Web.HttpUtility.UrlEncode("Editor$Edit$Advanced$txbExcerpt") + "=");
            //dataBuilder.Append("&Editor%24Edit%24Advanced%24txbTag=");
            dataBuilder.Append("&Editor%24Edit%24lkbPost=");
            dataBuilder.Append(System.Web.HttpUtility.UrlEncode("发布"));
            data = dataBuilder.ToString();

            responstr = GetResponse(uri2, "POST", data, uri2);

            Console.Write(responstr);
            Console.ReadLine();
        }

        public static string FireFoxAgent = "Mozilla/5.0 (Windows NT 5.2; rv:29.0) Gecko/20100101 Firefox/29.0";
        public static string IE7 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET4.0C; .NET4.0E)";
        public static string IE = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11";
        public static string IE8_Win2003 = "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
        public const string _defaultAcceptLanguage = "zh-cn,zh;q=0.5"; 
        public const string _defaultAcceptCharset = "GB2312,utf-8;q=0.7,*;q=0.7";

        public static CookieContainer CookieContainers = new CookieContainer();

        public static string GetResponse(string url, string method, string data,string referer,bool canDo = false)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.KeepAlive = true;
                req.Method = method.ToUpper();
                req.AllowAutoRedirect = true;
                req.CookieContainer = CookieContainers;
                req.ContentType = "application/x-www-form-urlencoded";

                req.UserAgent = FireFoxAgent;
                req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                req.Referer = referer;
                req.Timeout = 50000;

                if (method.ToUpper() == "POST" && data != null)
                {
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    byte[] postBytes = encoding.GetBytes(data); ;
                    req.ContentLength = postBytes.Length;
                    Stream st = req.GetRequestStream();
                    st.Write(postBytes, 0, postBytes.Length);
                    st.Close();
                }

                System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
                {
                    return true;
                };

                Encoding myEncoding = Encoding.GetEncoding("UTF-8");

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                CookiesString = req.CookieContainer.GetCookieHeader(req.RequestUri);
                if (canDo)
                {
                    foreach (Cookie cookie in res.Cookies)
                    {
                        InternetSetCookie("http://" + cookie.Domain.ToString(), cookie.Name.ToString(), cookie.Value.ToString());
                    }
                    Process.Start("IExplore.exe", "http://i.cnblogs.com/EditPosts.aspx?opt=1");
                }
                Stream resst = res.GetResponseStream();
                StreamReader sr = new StreamReader(resst, myEncoding);
                string str = sr.ReadToEnd();

                return str;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取用户登陆后下一次请求返回的内容
        /// </summary>
        public static string GetPage(string uri)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Method = "GET";
                request.KeepAlive = true;
                request.Headers.Add("Cookie:" + CookiesString);
                request.CookieContainer = CookieContainers;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();

                //设置cookie  
                CookiesString = request.CookieContainer.GetCookieHeader(request.RequestUri);
                //取再次跳转链接  
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string ss = sr.ReadToEnd();
  
                //Console.Write(ss);

                sr.Close();
                request.Abort();
                response.Close();
                //依据登陆成功后返回的Page信息,求出下次请求的url
                //每个网站登陆后加载的Url和顺序不尽相同,以下两步需根据实际情况做特殊处理,从而得到下次请求的URL
                //string[] substr = ss.Split(new char[] { '"' });
                //if (substr[1].Contains("ReturnUrl"))
                //{
                //    var subStr2 = substr[1].Substring(0, substr[1].IndexOf("ReturnUrl"));
                //    if (subStr2.Contains("http"))
                //    {
                //        NextRequestUrl = substr[1];
                //    }
                //    else
                //    {
                //        NextRequestUrl = "http://passport.cnblogs.com" + substr[1].Replace("%2f", "/").Replace("%3f","?").Replace("%3d","=").Replace("%3a",":");
                //    }
                return ss;
                //}
                //else
                //{
                //    NextRequestUrl = substr[1];
                //}
                //ResultHtml = ss;
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }
    }
}

 

posted @ 2014-05-08 17:32  颜骨柳筋才大如海  阅读(377)  评论(1编辑  收藏  举报