I'm trying to send push notifications via APNs via certificate based authentication (token based is not an option in my scenario). When I run the code, I get the following exceptions on SendAsync:
- HttpRequestException: Error while copying content to a stream.
- IOException: The write operation failed, see inner exception.
- WinHttpException: Error 12152 calling WinHttpWriteData, 'The server returned an invalid or unrecognized response'.
If I comment out the "handler.ClientCertificate.Add(_certificate)", no exceptions but I get a response status code of 403 and reason of "MissingProviderToken". So to mean this implies that it is able to establish a http2 connection.
I've been at the last two days so any help will be much appreciated!
var handler = new WinHttpHandler();
handler.ClientCertificateOption = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(_certificate);
handler.AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate;
HttpClient client = new HttpClient(handler);
var pushToken = "Base64EndocedDeviceTokenId";
var pushTokenByteArray = Convert.FromBase64String(pushToken);
var pushTokenHexString = BitConverter.ToString(pushTokenByteArray).Replace("-", "");
Dictionary<string, object> body;
body = new Dictionary<string, object>
{
{ "aps", new Dictionary<string, object>() { { "alert" , "Hello" } } },
};
var bodyStr = JsonConvert.SerializeObject(body);
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(bodyStr, Encoding.UTF8, "application/json"),
RequestUri = new Uri($"https://{_host}/3/device/{pushTokenHexString}"),
Version = new Version(2, 0)
};
requestMessage.Headers.Add("apns-push-type", "alert");
requestMessage.Headers.Add("apns-topic", "my.bundle.id");
requestMessage.Headers.Add("apns-priority", "10");
var response1 = client.SendAsync(requestMessage).Result;
var responseBody = response1.Content.ReadAsStringAsync().Result;