读书人

自动登录获取网页源码 500异常

发布时间: 2012-01-09 21:05:42 作者: rapoo

自动登录获取网页源码 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();


}
finally
{
if ( res != null )
{
res.Close();
}
}

return strResult;
}

在执行到 res = (HttpWebResponse)req.GetResponse();
时 出现System.Net.WebException: 远程服务器返回错误: (500) 内部服务器错误。 其他页面在获取的时候是没问题的,是什么原因?

[解决办法]
https://https-sec.xfab.com/fo/downloadstaticreport.do
https要包进证书进去才行

读书人网 >C#

热点推荐