I am trying to use the System.Net.HttpClient
class to post a message to Google Cloud Messaging.
Google Cloud Message requires you to include a header called "Authorization", in a format similar to this:
key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
But the HttpClient
class throws an exception when I try this.
string keyString = "key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Foo", keyString); // <== Proving I can
client.DefaultRequestHeaders.Add("Authorization", keyString); // Exception thrown
The exception is of type System.FormatException
. The message is
The format of value 'key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w' is invalid.
And the callstack is:
at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
at System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(String name, HeaderStoreItemInfo info, String value)
at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)
How can I get this header into this post request without an exception being thrown?
Headers:
User-Agent: Fiddler
Authorization: key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
Host: android.googleapis.com
Content-Length: 220
Content-Type: application/json
Request Body:
{
"registration_ids" : ["APA91bEM6XPdiZv5VgNNApakfyYfZwB871018Hljl1L27kaPvksasnR0bHlmcCZFxOSPD6bDLMZgvgfT9xsKnF6Tg0oSQM2cMM1KRbuK7cR7jICqAnSDYg_SvERTzPMT8puXGTlVkEVH6dsneBkXiBu6pZikWXWyRATAVbXnAHTe20-nQerb0"],
}
Try this answer instead:
https://stackoverflow.com/a/24575721/1981387
Seems like a bit of a workaround, since it's a string pair instead of a nice object, but it seems to work.
That's because your value is breaking the HTTP specification.
The header should contain Authorization: scheme SPACE value
as described here: http://www.ietf.org/rfc/rfc2617.txt
In your case:
Authorization: key AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With