Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I figured it out and got it working!</p> <p>While David's suggestions weren't the solution by themselves, he put me on the right track by telling me to use a packet sniffer (I ended up using Wireshark but that's not really the point).</p> <p>As it turns out, there were two errors in my dumbed down code. One so glaringly obvious that it makes me blush, one slightly more devious.</p> <p>First of all,</p> <pre><code>using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(Encoding.UTF8.GetBytes(requestText)); } </code></pre> <p>should of course be</p> <pre><code>using (var streamWriter = new StreamWriter(stream, Encoding.UTF8)) { streamWriter.Write(requestText); } </code></pre> <p>as streamWriter.Write does a ToString() on the parameter and Byte[].ToString() just returns "System.Byte[]". Embarassing!</p> <p>Secondly, the default UTF8 encoding adds the byte order mark \357\273\277, which also renders the content invalid as far as google is concerned. I found how to fix this problem <a href="https://stackoverflow.com/questions/1656717/c-sharp-httpwebrequest-posting-failing">here</a> on stackoverflow.</p> <p>So for anyone struggling with this, here is the final solution.</p> <pre><code>var url = string.Format ( "https://www.googleapis.com/calendar/v3/calendars?key={0}", application.Key ); var httpWebRequest = HttpWebRequest.Create(url) as HttpWebRequest; httpWebRequest.Headers["Authorization"] = string.Format("Bearer {0}", user.AccessToken.Token); httpWebRequest.Method = "POST"; // added the character set to the content-type as per David's suggestion httpWebRequest.ContentType = "application/json; charset=UTF-8"; httpWebRequest.CookieContainer = new CookieContainer(); // replaced Environment.Newline by CRLF as per David's suggestion var requestText = string.Join ( "\r\n", "{", " \"summary\": \"Test Calendar 123\"", "}" ); using (var stream = httpWebRequest.GetRequestStream()) // replaced Encoding.UTF8 by new UTF8Encoding(false) to avoid the byte order mark using (var streamWriter = new StreamWriter(stream, new UTF8Encoding(false))) { streamWriter.Write(requestText); } </code></pre> <p>Hope this helps someone!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload