第一个HttpWebResponse.GetResponseStream()失败,第二个工作?

时间:2011-03-13 04:22:12

标签: httpwebresponse getresponsestream

我正在创建一个程序,使用表单身份验证自动登录网站。当我调用我的方法连接到网站时,它会返回一个空的文档文本。但是,如果我第二次调用相同的方法,它会完美地运行。 这是我的代码:

//perform authentication and stores the session in the cookiecontainer
private void loginToSite()
{
// prepare the web page we will be asking for
request = (HttpWebRequest)
WebRequest.Create(@"http://diary.com/notes/my_journal");
request.KeepAlive = true;

//========================================
//start of forms authentication parameters
//========================================
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
//========================================
//end of forms authentication parameters
//========================================

request.ContentType = "text/html";

request.Method = "GET";
request.AllowAutoRedirect = true;
request.Referer = @"http://diary.com/";
request.CookieContainer = new CookieContainer();

// execute the request
HttpWebResponse response = (HttpWebResponse)
    request.GetResponse();

// we will read data via the response stream
Stream resStream = response.GetResponseStream();

container = request.CookieContainer;

//assign the http content to myWB for manipulation
    //myWB is a WebBrowser object that have been declared
myWB.DocumentStream = resStream;

//prevent script errors from popping up
myWB.ScriptErrorsSuppressed = true;

    MessageBox.Show(myWB.DocumentText);
}

0 个答案:

没有答案