Ejemplo n.º 1
0
        //[Test]
        public async void Get_Single_Html_Page_Https ()
        {
            var http2MsgHandler = new Http2MessageHandler ();
            var http = new HttpClient (http2MsgHandler);

            var data = await http.GetStringAsync ("https://localhost:8999/index.html");

            Assert.IsNotNullOrEmpty (data);
            Assert.IsTrue (data.Contains ("Hello World"));
        }
Ejemplo n.º 2
0
        //[Test]
        public async void Get_Single_Html_Page_Https()
        {
            var http2MsgHandler = new Http2MessageHandler();
            var http            = new HttpClient(http2MsgHandler);

            var data = await http.GetStringAsync("https://localhost:8999/index.html");

            Assert.IsNotNullOrEmpty(data);
            Assert.IsTrue(data.Contains("Hello World"));
        }
Ejemplo n.º 3
0
        public async void Get_Multiple_Html_Pages()
        {
            var http2MsgHandler = new Http2MessageHandler();
            var http            = new HttpClient(http2MsgHandler);

            for (var i = 0; i < 3; i++)
            {
                var data = await http.GetStringAsync("http://localhost:8999/index.html");

                Assert.NotEmpty(data);
                Assert.True(data.Contains("Hello World"));
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Token Based Authentication APNs 推播
        /// </summary>
        /// <param name="message">推播訊息</param>
        /// <param name="badge">badge數量</param>
        /// <param name="sound">推播聲音檔名</param>
        static async void TokenBasedAuthenticationAPNsPush(string message, int badge, string sound)
        {
            string algorithm = "ES256";

            string apnsKeyId   = "<apnsKeyId>";
            string teamId      = "<teamId>";
            string authKeyPath = @"<WE5.p8>";

            string bundleId       = "<bundleId>";
            string registrationId = "<registrationId>";

            //讀取下載的加密私鑰(.p8)
            var privateKeyContent = System.IO.File.ReadAllText(authKeyPath);
            var privateKey        = privateKeyContent.Replace("-----BEGIN PRIVATE KEY-----", String.Empty).Replace("-----END PRIVATE KEY-----", String.Empty).Replace("\n", String.Empty); // privateKeyContent.Split('\n')[1];

            var secretKeyFile = Convert.FromBase64String(privateKey);
            var secretKey     = CngKey.Import(secretKeyFile, CngKeyBlobFormat.Pkcs8PrivateBlob);

            var expiration        = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var expirationSeconds = (long)expiration.TotalSeconds;

            var payload = new Dictionary <string, object>()
            {
                { "iss", teamId },
                { "iat", expirationSeconds }
            };
            var header = new Dictionary <string, object>()
            {
                { "alg", algorithm },
                { "kid", apnsKeyId }
            };

            string accessToken = Jose.JWT.Encode(payload, secretKey, JwsAlgorithm.ES256, header);

            //Development server:api.development.push.apple.com:443
            //Production server:api.push.apple.com:443
            string host = "api.development.push.apple.com";
            int    port = 443;

            // Uri to request
            var uri = new Uri(string.Format("https://{0}:{1}/3/device/{2}", host, port, registrationId));

            var payloadData = JObject.FromObject(new
            {
                aps = new
                {
                    alert = message,
                    badge = badge,
                    sound = sound
                }
            });

            //UTF8編碼避免中文無法正常顯示
            byte[] data = System.Text.Encoding.UTF8.GetBytes(payloadData.ToString());

            var handler        = new Http2MessageHandler();
            var httpClient     = new HttpClient(handler);
            var requestMessage = new HttpRequestMessage();

            requestMessage.RequestUri = uri;
            requestMessage.Headers.Add("authorization", string.Format("bearer {0}", accessToken));
            requestMessage.Headers.Add("apns-id", Guid.NewGuid().ToString());
            requestMessage.Headers.Add("apns-expiration", "0");
            requestMessage.Headers.Add("apns-priority", "10");
            requestMessage.Headers.Add("apns-topic", bundleId);
            requestMessage.Method  = HttpMethod.Post;
            requestMessage.Content = new ByteArrayContent(data);

            try
            {
                var responseMessage = await httpClient.SendAsync(requestMessage);

                if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string responseUuid = string.Empty;
                    IEnumerable <string> values;
                    if (responseMessage.Headers.TryGetValues("apns-id", out values))
                    {
                        responseUuid = values.First();
                    }
                    Console.WriteLine(string.Format("\n\r*******Send Success [{0}]", responseUuid));
                }
                else
                {
                    var body = await responseMessage.Content.ReadAsStringAsync();

                    var json = new JObject();
                    json = JObject.Parse(body);

                    var reasonStr = json.Value <string>("reason");
                    Console.WriteLine("\n\r*******Failure reason => " + reasonStr);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\r*******Exception message => " + ex.Message);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="host_uri"></param>
        /// <param name="access_token"></param>
        /// <param name="payload_bytes"></param>
        /// <returns></returns>
        private async Task <(bool result, string message)> JwtAPNsPush(Uri host_uri, string access_token, byte[] payload_bytes)
        {
            var _result  = false;
            var _message = "";

            try
            {
                using (var _handler = new Http2MessageHandler())
                {
                    using (var _http_client = new HttpClient(_handler))
                    {
                        var _request_message = new HttpRequestMessage();
                        {
                            _request_message.RequestUri = host_uri;
                            _request_message.Headers.Add("authorization", string.Format("bearer {0}", access_token));
                            _request_message.Headers.Add("apns-id", Guid.NewGuid().ToString());
                            _request_message.Headers.Add("apns-expiration", "0");
                            _request_message.Headers.Add("apns-priority", "10");
                            _request_message.Headers.Add("apns-topic", BundleAppId);
                            _request_message.Method  = HttpMethod.Post;
                            _request_message.Content = new ByteArrayContent(payload_bytes);
                        }

                        var _response_message = await _http_client.SendAsync(_request_message);

                        if (_response_message.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var _response_uuid = "";

                            IEnumerable <string> values;
                            if (_response_message.Headers.TryGetValues("apns-id", out values))
                            {
                                _response_uuid = values.First();

                                _message = $"success: '{_response_uuid}'";
                                _result  = true;
                            }
                            else
                            {
                                _message = "failure";
                            }
                        }
                        else
                        {
                            var _response_body = await _response_message.Content.ReadAsStringAsync();

                            var _response_json = JObject.Parse(_response_body);

                            var _reason_str = _response_json.Value <string>("reason");
                            _message = $"failure: '{_reason_str}'";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _message = $"exception: '{ex.Message}'";
            }

            return(_result, _message);
        }