從新想象 Windows 8.1 Store Apps (90) - 通訊的新特性: 經過 HttpBaseProtocolFilter 實現 http 請求的緩存控制,以及 cookie 讀寫; 自

[源碼下載]


html

從新想象 Windows 8.1 Store Apps (90) - 通訊的新特性: 經過 HttpBaseProtocolFilter 實現 http 請求的緩存控制,以及 cookie 讀寫; 自定義 HttpFilter; 其餘



做者:webabcd


介紹
從新想象 Windows 8.1 Store Apps 之通訊的新特性html5

  • 經過 HttpBaseProtocolFilter 控制緩存邏輯,以及如何經過 HttpBaseProtocolFilter 管理 cookie
  • 自定義 HttpFilter
  • 其餘



示例
HTTP 服務端
WebServer/HttpDemo.aspx.csios

/*
 * 用於響應 http 請求
 */

using System;
using System.IO;
using System.Threading;
using System.Web;

namespace WebServer
{
    public partial class HttpDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 停 3 秒,以方便測試 http 請求的取消
            Thread.Sleep(3000);

            var action = Request.QueryString["action"];

            switch (action)
            {
                case "getString": // 響應 http get string 
                    Response.Write("hello webabcd: " + DateTime.Now.ToString("hh:mm:ss"));
                    break;
                case "getStream": // 響應 http get stream 
                    Response.Write("hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd hello webabcd");
                    break;
                case "postString": // 響應 http post string 
                    Response.Write(string.Format("param1:{0}, param2:{1}, referrer:{2}", Request.Form["param1"], Request.Form["param2"], Request.UrlReferrer));
                    break;
                case "postStream": // 響應 http post stream 
                    using (StreamReader reader = new StreamReader(Request.InputStream))
                    {
                        if (Request.InputStream.Length > 1024 * 100)
                        {
                            // 接收的數據太大,則顯示「數據接收成功」
                            Response.Write("數據接收成功");
                        }
                        else
                        {
                            // 顯示接收到的數據
                            string body = reader.ReadToEnd();
                            Response.Write(Server.HtmlEncode(body));
                        }
                    } 
                    break;
                case "uploadFile": // 處理上傳文件的請求
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        string key = Request.Files.GetKey(i);
                        HttpPostedFile file = Request.Files.Get(key);
                        string savePath = @"d:\" + file.FileName;

                        // 保存文件
                        file.SaveAs(savePath);

                        Response.Write(string.Format("key: {0}, fileName: {1}, savePath: {2}", key, file.FileName, savePath));
                        Response.Write("\n");
                    }
                    break;
                case "outputCookie": // 用於顯示服務端獲取到的 cookie 信息
                    for (int i = 0; i < Request.Cookies.Count; i++)
                    {
                        HttpCookie cookie = Request.Cookies[0];
                        Response.Write(string.Format("cookieName: {0}, cookieValue: {1}", cookie.Name, cookie.Value));
                        Response.Write("\n");
                    }
                    break;
                case "outputCustomHeader": // 用於顯示一個自定義的 http header
                    Response.Write("myRequestHeader: " + Request.Headers["myRequestHeader"]);
                    break;
                default:
                    break;
            }

            Response.End();
        }
    }
}


一、演示如何經過 HttpBaseProtocolFilter 控制緩存邏輯,以及如何經過 HttpBaseProtocolFilter 管理 cookie
HttpBaseProtocolFilterDemo.xamlweb

<Page
    x:Class="Windows81.Communication.HTTP.HttpBaseProtocolFilterDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.Communication.HTTP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" />

            <Button Name="btnCacheControl" Content="經過 HttpBaseProtocolFilter 控制緩存邏輯" Click="btnCacheControl_Click" Margin="0 10 0 0" />

            <Button Name="btnCookie" Content="經過 HttpBaseProtocolFilter 管理 cookie" Click="btnCookie_Click" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

HttpBaseProtocolFilterDemo.xaml.cs算法

/*
 * 演示如何經過 HttpBaseProtocolFilter 控制緩存邏輯,以及如何經過 HttpBaseProtocolFilter 管理 cookie
 * 
 * 
 * 注:
 * 一、HttpBaseProtocolFilter 實現了 IHttpFilter 接口(也就是說若是想要一個自定義 HttpFilter 的話,只要實現 IHttpFilter 接口便可)
 * 二、本例僅演示經過 HttpBaseProtocolFilter 控制緩存邏輯以及管理 cookie,HttpBaseProtocolFilter 的其它功能請參見文檔
 */

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
using Windows.Web.Http.Filters;

namespace Windows81.Communication.HTTP
{
    public sealed partial class HttpBaseProtocolFilterDemo : Page
    {
        private HttpClient _httpClient;
        private HttpBaseProtocolFilter _filter;

        public HttpBaseProtocolFilterDemo()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // 釋放資源
            if (_filter != null)
            {
                _filter.Dispose();
                _filter = null;
            }

            if (_httpClient != null)
            {
                _httpClient.Dispose();
                _httpClient = null;
            }            
        }

        // 演示如何經過 HttpBaseProtocolFilter 控制緩存邏輯
        private async void btnCacheControl_Click(object sender, RoutedEventArgs e)
        {
            _filter = new HttpBaseProtocolFilter();

            // 實例化 HttpClient 時,指定此 HttpClient 所關聯的 IHttpFilter 對象
            _httpClient = new HttpClient(_filter);

            try
            {
                // 獲取到 http 響應的數據後寫入緩存的行爲
                //     NoCache - 不寫入緩存
                //     Default - 默認行爲,通常會寫入緩存(默認值)
                _filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

                // 請求 http 時,從緩存獲取數據的邏輯
                //     Default - 使用 RFC 2616 中由 IETF 指定的緩存算法(默認值)
                //     MostRecent - 儘量使用本地 HTTP 緩存,但應始終詢問服務器是否有更新的內容可用
                //     OnlyFromCache - 只使用本地 HTTP 緩存中的數據,適合脫機的場景
                _filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;

                HttpResponseMessage response = await _httpClient.GetAsync(new Uri("http://localhost:39630/HttpDemo.aspx?action=getString"));

                lblMsg.Text += ((int)response.StatusCode) + " " + response.ReasonPhrase;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += await response.Content.ReadAsStringAsync();
                lblMsg.Text += Environment.NewLine;
            }
            catch (Exception ex)
            {
                lblMsg.Text += ex.ToString();
                lblMsg.Text += Environment.NewLine;
            }
        }

        // 演示如何經過 HttpBaseProtocolFilter 管理 cookie
        private async void btnCookie_Click(object sender, RoutedEventArgs e)
        {
            _httpClient = new HttpClient();

            try
            {
                // 構造一個 cookie(須要指定 cookie 的 name, domain, path)
                HttpCookie cookie = new HttpCookie("name", "localhost", "/");
                cookie.Value = "webabcd";
                cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Secure = false;
                cookie.HttpOnly = false;

                // 經過 HttpBaseProtocolFilter 寫入 cookie(也能夠獲取 cookie 或者刪除 cookie)
                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                bool replaced = filter.CookieManager.SetCookie(cookie, false);

                // 請求 http 時會帶上相應的 cookie
                HttpResponseMessage response = await _httpClient.GetAsync(new Uri("http://localhost:39630/HttpDemo.aspx?action=outputCookie"));

                lblMsg.Text += ((int)response.StatusCode) + " " + response.ReasonPhrase;
                lblMsg.Text += Environment.NewLine;

                lblMsg.Text += await response.Content.ReadAsStringAsync();
                lblMsg.Text += Environment.NewLine;
            }
            catch (Exception ex)
            {
                lblMsg.Text += ex.ToString();
                lblMsg.Text += Environment.NewLine;
            }
        }
    }
}


二、演示如何使用自定義的 HttpFilter
MyHttpFilter.csexpress

/*
 * 實現 IHttpFilter 接口,開發一個自定義的 HttpFilter
 * 
 * 
 * 本 HttpFilter 會在請求和響應的 http header 中添加一條自定義數據
 */

using System;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Web.Http;
using Windows.Web.Http.Filters;

namespace Windows81.Communication.HTTP
{
    public class MyHttpFilter : IHttpFilter
    {
        private HttpBaseProtocolFilter _innerFilter;

        public MyHttpFilter()
        {
            _innerFilter = new HttpBaseProtocolFilter();
        }

        // IHttpFilter 惟一的一個須要實現的方法
        public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(async (cancellationToken, progress) =>
            {
                // 添加一個自定義 request http header
                request.Headers.Add("myRequestHeader", "request webabcd");

                // 借用 HttpBaseProtocolFilter 來完成 SendRequestAsync() 的工做
                HttpResponseMessage response = await _innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);

                cancellationToken.ThrowIfCancellationRequested();

                // 添加一個自定義 response http header
                response.Headers.Add("myResponseHeader", "response webabcd");

                return response;
            });
        }

        public void Dispose()
        {
            _innerFilter.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}

CustomHttpFilter.xamlwindows

<Page
    x:Class="Windows81.Communication.HTTP.CustomHttpFilter"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.Communication.HTTP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" />

            <Button Name="btnDemo" Content="自定義 HttpFilter" Click="btnDemo_Click" Margin="0 10 0 0" />

            <Button Name="btnCancel" Content="cancel" Click="btnCancel_Click" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

CustomHttpFilter.xaml.cs緩存

/*
 * 演示如何使用自定義的 HttpFilter
 * 
 * 
 * 自定義 HttpFilter 須要實現 IHttpFilter 接口,請參見:MyHttpFilter.cs
 */

using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;

namespace Windows81.Communication.HTTP
{
    public sealed partial class CustomHttpFilter : Page
    {
        private HttpClient _httpClient;
        private CancellationTokenSource _cts;

        // 自定義的 HttpFilter
        private MyHttpFilter _filter;

        public CustomHttpFilter()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // 釋放資源
            if (_filter != null)
            {
                _filter.Dispose();
                _filter = null;
            }

            if (_httpClient != null)
            {
                _httpClient.Dispose();
                _httpClient = null;
            }

            if (_cts != null)
            {
                _cts.Dispose();
                _cts = null;
            }
        }

        private async void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            _filter = new MyHttpFilter();

            // 實例化 HttpClient 時,指定此 HttpClient 所關聯的 IHttpFilter 對象
            _httpClient = new HttpClient(_filter);

            _cts = new CancellationTokenSource();

            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(new Uri("http://localhost:39630/HttpDemo.aspx?action=outputCustomHeader")).AsTask(_cts.Token);

                lblMsg.Text += ((int)response.StatusCode) + " " + response.ReasonPhrase;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "myResponseHeader: " + response.Headers["myResponseHeader"];
                lblMsg.Text += Environment.NewLine;

                // IHttpContent.ReadAsStringAsync() - 獲取 string 類型的響應數據
                // IHttpContent.ReadAsBufferAsync() - 獲取 IBuffer 類型的響應數據
                // IHttpContent.ReadAsInputStreamAsync() - 獲取 IInputStream 類型的響應數據
                lblMsg.Text += await response.Content.ReadAsStringAsync();
                lblMsg.Text += Environment.NewLine;
            }
            catch (TaskCanceledException)
            {
                lblMsg.Text += "取消了";
                lblMsg.Text += Environment.NewLine;
            }
            catch (Exception ex)
            {
                lblMsg.Text += ex.ToString();
                lblMsg.Text += Environment.NewLine;
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            // 取消 http 請求
            if (_cts != null)
            {
                _cts.Cancel();
                _cts.Dispose();
                _cts = null;
            }
        }
    }
}


三、其餘
Other.xaml服務器

<Page
    x:Class="Windows81.Communication.Other"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.Communication"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap">
                <Run>一、實時通訊支持 Windows.Web.Http API 了(仍然要求 app 必須在鎖屏上),關於實時通訊請參見:http://www.cnblogs.com/webabcd/archive/2013/10/28/3391694.html</Run>
                <LineBreak />
                <Run>二、增長了對 Geofence 的支持,即某設備在進入或退出某地理區域後能夠向 app 發出通知。Windows.Devices.Geolocation.Geofencing 命名空間用於 Geofence 管理, LocationTrigger 用於後臺任務觸發 Geofence 事件</Run>
                <LineBreak />
                <Run>三、支持設備的 WiFi 直連,參見 Windows.Devices.WifiDirect 命名空間</Run>
            </TextBlock>

        </StackPanel>
    </Grid>
</Page>



OK
[源碼下載]cookie

相關文章
相關標籤/搜索