通过 HTTP 请求,我登录到页面:https ://secure.bodytel.com/de/mybodytel.html 。之后我想阅读设置(https://secure.bodytel.com/de/mybodytel/settings.html)。所以这是我的问题:我发送了第二个请求,页面告诉我我没有登录了。当我用 fiddler 调试东西时,我看到我有两个不同的 cookie ID。那么,我怎样才能让 cookie 保持活力呢?或随我的要求发送。
我已经阅读了这篇文章:“http://stackoverflow.com/questions/11596378/getting-a-page-source-after-post-variables-have-been-sent”,但它对我没有多大帮助。
这是我的代码:使用 System.Text;使用 System.Windows;使用 System.Windows.Controls;使用 System.Windows.Forms;使用 System.Net;使用 System.IO;使用 System.Web;
namespace BodytelConnection
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void loginBtn_Click(object sender, RoutedEventArgs e)
{
#region username stuff
string benutzername = textBox_benutzername.ToString();
string passwort = textBox_passwort.ToString();
passwort = changeString(passwort);
benutzername = changeString(benutzername);
#endregion username stuff
CookieCollection cookies = new CookieCollection();
CookieContainer container = new CookieContainer();
#region login
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("https://secure.bodytel.com/de/mybodytel.html");
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.AllowWriteStreamBuffering = true;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes("login=" + benutzername + "&password=" + passwort + "&step=login");
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
StreamReader sr = new StreamReader(getResponse.GetResponseStream());
// here im trying to save the cookie
container.Add(getResponse.Cookies);
getRequest.CookieContainer = container;
string source = sr.ReadToEnd();
// save the html
StreamWriter myWriter = File.CreateText(@"C:\Users\nicholas\Documents\Visual Studio 2010\Projects\BodytelConnection\BodytelConnection\bin\\Debug\test.txt");
myWriter.Write(source);
myWriter.Close();
#endregion login
//read the settings
#region readSettings
getRequest.Method = WebRequestMethods.Http.Get;
getRequest = (HttpWebRequest)WebRequest.Create("https://secure.bodytel.com/de/mybodytel/settings.html");
getRequest.AllowWriteStreamBuffering = true;
getResponse = (HttpWebResponse)getRequest.GetResponse();
sr = new StreamReader(getResponse.GetResponseStream());
source = sr.ReadToEnd();
StreamWriter myWriter2 = File.CreateText(@"C:\Users\nicholas\Documents\Visual Studio 2010\Projects\BodytelConnection\BodytelConnection\bin\\Debug\test2.txt");
myWriter2.Write(source);
myWriter2.Close();
getResponse.Close();
#endregion readSettings
}
private string changeString(string myString)
{
myString = myString.Replace("System.Windows.Controls.TextBox: ", "");
return myString;
}
}
}