日期:2014-05-18  浏览次数:20480 次

用HttpWebRequest POST提交表单的问题
代码都是网上找的,大同小异。

我想获取网站登录后才能访问的页面,就像有些论坛限制了必须注册用户才能浏览那样。


要登录网站使用的是Session验证,首先用POST提交用户名、密码到登陆的URL,然后再获取需要验证通过以后的另外一个页面的URL。但是获取数据的时候拿到的只是没有登陆会被直动转向的页面,发送跟读取HttpWebRequest使用的不是同一个对象,是不是这里有问题。

因为HttpWebRequest对象建立以后不能更改URL只好在新建一个。

谁有没问题的POST代码麻烦给一段

------解决方案--------------------
hdt(倦怠)的方法不行我就是用这个方法来POST需要提交需要的用户名、密码。

我刚看了一下登录的记录根本没有登录。

==================
因为b/s是无状态的,你提交一个用户名密码,成功后服务器端会返回一个票据,
这要看服务器如何验证身份的,如果是asp.net 利用session 来判断登陆用户 ,一般session是通过客户端提交一个名字sessionid的cookie,来确定身份,你的任务就是捕作这个sessionid,在提交回去,而不是简简单单每次提交一个用户名和密码。

------解决方案--------------------
要把对方回传的cookie保存起来,在再次请求的时候提供cookie,说到底,session也要靠cookie来保持sessionid的

request.CookieContainer

response.Cookies
------解决方案--------------------
VIEWSTAT是要的
public static string GetPostBackString(string pageHtml,string url, string eventTarget, string eventArg,Encoding encoding)
{

// extract the viewstate value from the login dialog page.
// We need to post this back,
// along with the username and password
string viewState = GetViewState(pageHtml);

// build postback string
// This string will vary depending on the page. The best
// way to find out what your postback should look like is to
// monitor a normal login using a utility like TCPTrace.
string postback =
String.Format( "__VIEWSTATE={0}&__EVENTTARGET={1} " +
"&__EVENTARGUMENT={2} ",
viewState, eventTarget,eventArg);


// our second request is the POST of the username / password data.
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(url);


request.Method = "POST ";
request.ContentType = "application/x-www-form-urlencoded ";

request.Timeout = 300000;
// write our postback data into the request stream
StreamWriter writer =
new StreamWriter(request.GetRequestStream());
writer.Write(postback);
writer.Close();


HttpWebResponse response=null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch(WebException)
{
response = (HttpWebResponse)request.GetResponse();
}
Stream stream = response.GetResponseStream();
string page = new StreamReader(stream, encoding).ReadToEnd();


if (stream != null) stream.Close();
if (response != null) response.Close();

// our webpage data is in the 'page ' string.
//Console.WriteLine(page);
return page;
}

private static string GetViewState(string aspxPage)
{
Regex regex =
new Regex( "(? <=(__viewstate\ ".value.\ ")).*(?=\ "./> ) ", RegexOptions.IgnoreCase);

Match match =
regex.Match(aspxPage);


return System.Web.HttpUtility.UrlEncode(match.Value);
}