7

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?


Incidentally, I have composed a post like this using Fiddler, and it works:

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"],
}
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205

2 Answers2

7

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.

Community
  • 1
  • 1
welegan
  • 3,013
  • 3
  • 15
  • 20
6

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
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • 3
    It might break the specification, but unfortunately that's what I have to put in to get the Google Cloud Messaging server to accept my message. – Andrew Shepherd May 08 '14 at 07:32
  • 2
    then you need to use the `HttpWebRequest` class instead. – jgauffin May 08 '14 at 07:55
  • 3
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX"); See http://stackoverflow.com/a/24575721/143195 – JCallico Jul 20 '16 at 17:42