目的:用.net代码登录.net并且提交文章一篇
注意:对于asp.net页面中的post请求服务器端会对提交的__VIEWSTATE、__EVENTVALIDATION验证,所以请求时需要提交这两个字段内容
获取__VIEWSTATE、__EVENTVALIDATION两个字段内容,且提交数据登录园子
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24class="csharp plain">
//获取到url页面的html内容
var loginpagehtml = RequestHelper.GetResponseContent(url);
//获取页面中的__VIEWSTATE, __EVENTVALIDATION
__VIEWSTATE = Regex.Match(loginpagehtml, reg1).Groups[1].Value;
__EVENTVALIDATION = Regex.Match(loginpagehtml, reg2).Groups[1].Value;
//提交的数据字典
Dictionary<
string
,
string
> dicdata =
new
Dictionary<
string
,
string
>()
{
{
"__VIEWSTATE"
,__VIEWSTATE},
{
"__EVENTVALIDATION"
, __EVENTVALIDATION},
{
"tbUserName"
,
"username"
},
{
"tbPassword"
,
"password"
},
{
"__EVENTTARGET"
,
""
},
{
"__EVENTARGUMENT"
,
""
},
{
"btnLogin"
,
"登 录"
}
};
//拼接提交的数据字典为a=1&b=2格式
var postdata = dicdata.Select(dic =>
string
.Format(
"{0}={1}"
, dic.Key, dic.Value)).Aggregate((a, b) => a +
"&"
+ b);
//提交登录页面request,并且获取response对象
var response = RequestHelper.GetResponse(url, postdata, (head) => { head.Method =
"POST"
; head.UserAgent =
"Mozilla/5.0"
; head.CookieContainer = cc; });
登录后到发表文章页面提交文章一篇,代码如下:
?//提交一篇文章
var editpostpagehtml = RequestHelper.GetResponseContent(
"http://www.cnblogs.com/lyroge/admin/EditPosts.aspx?opt=1"
,
null
, (head) => { head.CookieContainer = cc; head.AllowAutoRedirect =
true
; });
__VIEWSTATE = Regex.Match(editpostpagehtml, reg1).Groups[1].Value;
var dicdata =
new
Dictionary<
string
,
string
>()
{
{
"__VIEWSTATE"
,__VIEWSTATE},
{
"__EVENTTARGET"
,
""
},
{
"__EVENTARGUMENT"
,
""
},
{
"Editor$Edit$lkbPost"
,
"发布"
},
{
"Editor$Edit$txbTitle"
,
".net 登录博客园 并且发表文章一篇"
},
{
"Editor$Edit$EditorBody"
,
"<p>内容我自己填写</p>"
},
{
"Editor$Edit$APOptions$APSiteHome$chkDisplayHomePage"
,
"on"
},
{
"Editor$Edit$Advanced$ckbPublished"
,
"on"
},
{
"Editor$Edit$Advanced$chkComments"
,
"on"
},
{
"Editor$Edit$Advanced$chkMainSyndication"
,
"on"
},
{
"Editor$Edit$Advanced$txbEntryName"
,
""
},
{
"Editor$Edit$Advanced$txbExcerpt"
,
""
},
{
"Editor$Edit$Advanced$txbTag"
,
""
},
{
"Editor$Edit$Advanced$tbEnryPassword"
,
""
}
};
//注意对提交的数据要进行urlencode编码
var postdata = dicdata.Select(dic =>
string
.Format(
"{0}={1}"
, System.Web.HttpUtility.UrlEncode(dic.Key), System.Web.HttpUtility.UrlEncode(dic.Value))).Aggregate((a, b) => a +
"&"
+ b);
var response = RequestHelper.GetResponse(
"http://www.cnblogs.com/lyroge/admin/EditPosts.aspx?opt=1"
, postdata, (head) =>
{
head.Method =
"POST"
; head.UserAgent =
"Mozilla/5.0"
; head.CookieContainer = cc; head.Referer =
"http://www.cnblogs.com"
;
});
http://www.cnblogs.com/lyroge/archive/2012/03/29/2423060.html