自动登录获取网页源码 500错误!
private void btnDownload_Click(object sender, System.EventArgs e)
{
string strResult;
if (HttpContext.Current.Application[ "cookieheader "] != null)
{
cookieheader = (string)HttpContext.Current.Application[ "cookieheader "];
}
else
{
//Login into the website and keep the cookie for the session in the application variable
string strLogin = Login( "https://https-sec.xfab.com/fo/logon.do ", "username=username&password=password ") ;
}
strResult = getPage( "https://https-sec.xfab.com/fo/downloadstaticreport.do ", "id=0 ") ;
}
public static string getPage(String url, String paramList)
{
HttpWebResponse res = null;
string strResult = " ";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST ";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded ";
CookieContainer cookieCon = new CookieContainer();
req.CookieContainer = cookieCon;
req.CookieContainer.SetCookies(new Uri(url),cookieheader);
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = { '? ', '= ', '& '};
byte[] SomeBytes = null;
if (paramList != null)
{
int i=0, j;
while(i <paramList.Length)
{
j=paramList.IndexOfAny(reserved, i);
if (j==-1)
{
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
UrlEncoded.Append(paramList.Substring(j,1));
i = j+1;
}
SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
}
else
{
req.ContentLength = 0;
}
res = (HttpWebResponse)req.GetResponse();
Stream ReceiveStream = res.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding( "utf-8 ");
StreamReader sr = new StreamReader( ReceiveStream, encode );
Char[] read = new Char[256];
int count = sr.Read( read, 0, 256 );
while (count > 0)
{
String str = new String(read, 0, count);
strResult += str;
count = sr.Read(read, 0, 256);
}
}
catch(Exception e)
{
strResult = e.ToString();