http推送接收範例



http推送接收範例(此範例是以.net C#製作)


網頁前端的部分,什麼都不需要,只要開啟一個空白的頁面就可以了

如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>


後置程式碼的部分,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;   //處理xml使用
using System.Security.AccessControl;   //處理資料夾的權限

public partial class _Default : System.Web.UI.Page
{
    string dir = @"C:\MyDocument\SaveCapFileHere\";     //這邊設定要接收的資料夾路徑
    protected void Page_Load(object sender, EventArgs e)
    {
        string name = Request["name"] == null ? "" : Request["name"];    //所要接收的檔案名稱 

        if(name!="")    
        {
            XmlDocument xd = new XmlDocument();
            string str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <Data><Status>{0}</Status></Data>";
            try
            {
                xd.Load(Request.InputStream);
                if (!System.IO.Directory.Exists(dir))             //若是指定的存檔路徑不存在則建立
                {
                    System.IO.Directory.CreateDirectory(dir);
                    SetFileRole(dir);
                    //設定資料夾的權限,這邊是讓所有人都可以存取,有相當的風險,可以自行修改成合適的權限
                }

                xd.Save(dir + name);  //儲存檔案 
                str = string.Format(str, true);
            }
            catch(Exception ex)
            {
                str = string.Format(str, false);
            }

            Response.Clear();
            Response.ContentType = "text/xml";
            XXXXXXXXXXXXXX(str);  //回應接收狀態
            Response.Flush();
            Response.End();
        }

    }

    public static void SetFileRole(string foldPath)   //設定資料夾的存取權限
    {
        DirectorySecurity fsec = new DirectorySecurity();
        fsec.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl,
        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
        System.IO.Directory.SetAccessControl(foldPath, fsec);
    }
}


在申請推送時,可以先利用提供的「測試發送」功能測試一下設定的連線會不會有問題




如果測試是成功的話,應該會看到如下的訊息:


在網址填寫有誤的時候則是會出現錯誤的提示:


同時伺服器會發送一個測試的檔案,檔案名稱為"www",到設定接收的資料夾可以看到該檔案。



檔案中的內容很簡單,打開來看是這個樣子。





下載範例程式