创建网页登录会话

本文关键字:会话 登录 网页 创建 | 更新日期: 2023-09-27 17:50:21

我希望我在这里问正确的方式,因为这是我第一次在stackoverflow。我是c#和WP8的新手,但我正在做一个小项目,我通过我的WP8应用程序登录到我的页面,然后我的愿望是能够在登录后,以某种方式使用登录的会话/cookie在web浏览器控件中导航,通过其他"受保护"的页面。我确实搜索了论坛和网络,但我没有在其他地方找到具体的答案。下面我有我的登录会话,它的工作和"结果"给了我登录后的页面的HTML。但是我有点卡住了……也许有更好/更聪明/更简单的方法?

致以最亲切的问候马丁

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HTTPPost.Resources;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace HTTPPost
{
public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainPage_Loaded);
    }
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        System.Uri myUri = new System.Uri("http://homepage.com/index.php");
        HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
    }
    void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        // End the stream request operation
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);
        // Create the post data
        string postData = "user=usernamepass=password";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Add the post data to the web request
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
        // Start the web request
        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
    }
    void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result;
            result = httpWebStreamReader.ReadToEnd();
            MiniBrowser.NavigateToString(result);
            Debug.WriteLine(result);
        }
    }
}
}

创建网页登录会话

关于获取和存储cookie有很多答案,但我有一个避免使用它们的技巧。诀窍是在登录序列之后对该页面上的所有请求使用相同的WebClient实例。查看我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SomeApp
{
    public class WebRequests
    {
        //Making property of HttpClient
        private static HttpClient _client;
        public static HttpClient Client
        {
            get { return _client; }
            set { _client = value; }
        }
        //method to download string from page
        public static async Task<string> LoadPageAsync(string p)
        {
            if (Client == null)// that means we need to login to page
            {
                Client = await Login(Client);
            }
            return await Client.GetStringAsync(p);
        }
        // method for logging in
        public static async Task<HttpClient> Login(HttpClient client)
        {
            client = new HttpClient();
            var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("email", "someone@example.com"),
                    new KeyValuePair<string, string>("password", "SoMePasSwOrD")
                });
            var response = await client.PostAsync("https://www.website.com/login.php", content);
            return client;
        }
        var page1Html = await LoadPageAsync("https://www.website.com/page1.php");

    }
}