Partager via


How to get and set cookies for Windows Phone 8

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

To set cookies on a request message

  1. Create a System.Net..::.CookieContainer object for the HttpWebRequest..::.CookieContainer property of the HttpWebRequest.

    request.CookieContainer = New CookieContainer()
    
    request.CookieContainer = new CookieContainer();
    
  2. Add cookie objects to the HttpWebRequest..::.CookieContainer by using the CookieContainer..::.Add method.

    request.CookieContainer.Add(New Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
                                New Cookie("id", "1234"))
    
    request.CookieContainer.Add(new Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
        new Cookie("id", "1234"));
    

To get cookies on a response message

  1. Create a System.Net..::.CookieContainer on the request to hold cookie objects that are sent on the response. You must do this even if you are not sending any cookies.

    request.CookieContainer = New CookieContainer()
    
    request.CookieContainer = new CookieContainer();
    
  2. Retrieve the values in the HttpWebResponse..::.Cookies property of HttpWebResponse. In this example, the cookies are retrieved and saved to isolated storage.

    Private Sub ReadCallback(asynchronousResult As IAsyncResult)
        Dim request As HttpWebRequest = DirectCast(asynchronousResult.AsyncState, HttpWebRequest)
        Dim response As HttpWebResponse = DirectCast(request.EndGetResponse(asynchronousResult), HttpWebResponse)
        Using isf As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
            Using isfs As IsolatedStorageFileStream = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write)
                Using sw As New StreamWriter(isfs)
                    For Each cookieValue As Cookie In response.Cookies
                        sw.WriteLine("Cookie: " & cookieValue.ToString())
                    Next
                    sw.Close()
                End Using
    
            End Using
        End Using
    End Sub
    
    private void ReadCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)
            request.EndGetResponse(asynchronousResult);
        using (IsolatedStorageFile isf =
            IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
                FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(isfs))
                {
                    foreach (Cookie cookieValue in response.Cookies)
                    {
                        sw.WriteLine("Cookie: " + cookieValue.ToString());
                    }
                    sw.Close();
                }
            }
    
        }
    }
    

Example

The following sample demonstrates how to create a Web request and add a cookie to the request. It also demonstrates how to extract the cookies from the Web response, write them to a file in isolated storage, and read them from isolated storage. When you run this sample, it displays the System.Net..::.Cookie values in a TextBlock control.

Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Net.Browser
Imports System.IO
Imports System.Text
Imports System.IO.IsolatedStorage
Imports Microsoft.Phone.Controls


Partial Public Class MainPage
    Inherits PhoneApplicationPage

    Public Sub New()

        InitializeComponent()
    End Sub

    Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
        InitializeWebRequestClientStackForURI()
        ReadFromIsolatedStorage()
    End Sub

    Private Sub InitializeWebRequestClientStackForURI()

        ' Create a HttpWebRequest.
        Dim request As HttpWebRequest = DirectCast(WebRequest.Create
            (New Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx")), HttpWebRequest)

        'Create the cookie container and add a cookie.
        request.CookieContainer = New CookieContainer()


        ' This example shows manually adding a cookie, but you would most
        ' likely read the cookies from isolated storage.
        request.CookieContainer.Add(New Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
                                    New Cookie("id", "1234"))

        ' Send the request.
        request.BeginGetResponse(New AsyncCallback(AddressOf ReadCallback), request)
    End Sub

    ' Get the response and write cookies to isolated storage.
    Private Sub ReadCallback(asynchronousResult As IAsyncResult)
        Dim request As HttpWebRequest = DirectCast(asynchronousResult.AsyncState, HttpWebRequest)
        Dim response As HttpWebResponse = DirectCast(request.EndGetResponse(asynchronousResult), HttpWebResponse)
        Using isf As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
            Using isfs As IsolatedStorageFileStream = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write)
                Using sw As New StreamWriter(isfs)
                    For Each cookieValue As Cookie In response.Cookies
                        sw.WriteLine("Cookie: " & cookieValue.ToString())
                    Next
                    sw.Close()
                End Using

            End Using
        End Using
    End Sub
    Private Sub ReadFromIsolatedStorage()
        Using isf As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
            Using isfs As IsolatedStorageFileStream = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate)
                Using sr As New StreamReader(isfs)
                    tb1.Text = sr.ReadToEnd()
                    sr.Close()
                End Using

            End Using
        End Using
    End Sub
End Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.Browser;
using System.IO;
using System.Text;
using System.IO.IsolatedStorage;


namespace CookiesEx
{
    public partial class MainPage : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            InitializeWebRequestClientStackForURI();
            ReadFromIsolatedStorage();
        }

        private void InitializeWebRequestClientStackForURI()
        {

            // Create a HttpWebRequest.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"));

            //Create the cookie container and add a cookie.
            request.CookieContainer = new CookieContainer();


            // This example shows manually adding a cookie, but you would most
            // likely read the cookies from isolated storage.
            request.CookieContainer.Add(new Uri("https://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"),
                new Cookie("id", "1234"));

            // Send the request.
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        // Get the response and write cookies to isolated storage.
        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)
                request.EndGetResponse(asynchronousResult);
            using (IsolatedStorageFile isf =
                IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
                    FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(isfs))
                    {
                        foreach (Cookie cookieValue in response.Cookies)
                        {
                            sw.WriteLine("Cookie: " + cookieValue.ToString());
                        }
                        sw.Close();
                    }
                }

            }
        }
        private void ReadFromIsolatedStorage()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isfs =
                   isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate))
                {
                    using (StreamReader sr = new StreamReader(isfs))
                    {
                        tb1.Text = sr.ReadToEnd();
                        sr.Close();
                    }
                }

            }
        }


    }
}
<phone:PhoneApplicationPage x:Class="CookiesEx.MainPage" 
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800">
    <StackPanel x:Name="LayoutRoot" Width="390">
         <Button Width="372" Height="173" Content="Click to send request" 
                HorizontalAlignment="Left"
                x:Name="button1" Click="button1_Click" Margin="5"/>
        <TextBlock TextWrapping="Wrap" Foreground="{StaticResource PhoneForegroundBrush}" Height="267" Name="tb1" Width="382" FontSize="22" />
    </StackPanel>
</phone:PhoneApplicationPage>

Compiling the Code

  • In Visual Studio, create a new Windows Phone Application project named CookiesEx.

  • Copy and paste the code for MainPage.xaml and MainPage.xaml.cs or MainPage.xaml.vb, replacing the file contents.