创建到网页的登录会话

时间:2014-03-15 16:46:42

标签: c# cookies windows-phone-8 login

我希望我在这里以正确的方式提问,因为它是我在stackoverflow中的第一个。 我是C#和WP8的新手,但我正在开发一个小项目,我通过我的WP8应用程序登录到我的页面,然后我希望能够在登录后以某种方式使用会话/ cookie来自登录以通过另一个" protected"在WebBrowser控件中导航页面。 我确实搜索了论坛和网络,但我没有在其他地方找到具体的答案。 下面我的登录会话有效,"结果"登录后给我页面的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);
        }
    }
}
}

1 个答案:

答案 0 :(得分:1)

嗯,有很多关于获取和存储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");


    }
}