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

未处理的“System.Net.WebException”类型的异常出现在 System.dll 中 基础连接已经关闭: 连接被意外关闭
错误如标题:
代码如下:每当运行到红色代码处就出错了。
public static bool GetLogin(string userName, string password)
{
bool result = false;
GetInitialCookies(userName);
Thread.Sleep(1000*5);

Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");

string postUrl = "https://passport.baidu.com/?login";
StringBuilder postString = new StringBuilder();
postString.Append("tpl_ok=");
postString.Append("&next_target=");
postString.Append("&tpl=");
postString.Append("&skip_ok=");
postString.Append("&aid=");
postString.Append("&need_pay=");
postString.Append("&need_coin=");
postString.Append("&pay_method=");
postString.Append("&u=.%2F");
postString.Append("&return_method=get");
postString.Append("&more_param=");
postString.Append("&return_type=");
postString.Append("&psp_tt=0");
postString.Append("&password=" + HttpUtility.UrlEncode(password,encoding));
postString.Append("&safeflg=0");
postString.Append("&username=" +HttpUtility.UrlEncode(userName,encoding));
postString.Append("&verifycode=");
postString.Append("&mem_pass=on");//记住密码

byte[] postBytes = encoding.GetBytes(postString.ToString());

HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(postUrl);
request.Method = "POST";
request.Timeout = 1000*60;
request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
request.Referer = "http://passport.baidu.com/center";
request.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5");
request.Headers.Add("Accept-Charset", "gb2312,utf-8;q=0.7,*;q=0.7");
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Accept-Encoding", "gzip, deflate");
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727)";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6";
request.KeepAlive = true;
//request.Headers.Add("Host", "passport.baidu.com");
//request.Headers[HttpRequestHeader.Host] = "passport.baidu.com "; 
request.Headers.Add("Cache-Control", "no-cache");
request.ContentLength = postBytes.Length;
request.AllowAutoRedirect = false;
//request.CookieContainer.Add()


System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

request.CookieContainer = BlogCookies;

using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);

}

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //response.Headers.Add("P3P", "CP=CAO PSA OUR");

BlogCookies.Add(response.Cookies);

StreamReader respStream = new StreamReader(response.GetResponseStream(), encoding);
string resutlContent = respStream.ReadToEnd();
respStream.Close();
response.Close();
FileUtility.Log("baidu:通过用户名和密码实现登录");
if(resutlContent.IndexOf("location.href=url;")>0)
{
FileUtility.Log("baidu:登录成功");
result = true;

#region 把登录成功后获得的cookies写到文件中
strin