c# HttpWebRequest POST'ing failing

KJ Tsanaktsidis picture KJ Tsanaktsidis · Nov 1, 2009 · Viewed 11.7k times · Source

So i'm trying to POST something to a webserver.

System.Net.HttpWebRequest EventReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("url");
System.String Content = "id=" + Id;
EventReq.ContentLength = System.Text.Encoding.UTF8.GetByteCount(Content);
EventReq.Method = "POST";
EventReq.ContentType = "application/x-www-form-urlencoded";
System.IO.StreamWriter sw = new System.IO.StreamWriter(EventReq.GetRequestStream(), System.Text.Encoding.UTF8);
sw.Write(Content);
sw.Flush();
sw.Close();

Looks alright, i'm setting content-length based on the size of the ENCODED data... Anyway it fails at sw.flush() with "bytes to be written to the stream exceed the Content-Length size specified"

Is StreamWriter doing some magic behind my back i'm not aware of? Is there a way i can peer into what StreamWriter is doing?

Answer

Jon Skeet picture Jon Skeet · Nov 1, 2009

Other answers have explained how to avoid this, but I thought I'd answer why it's happening: you're ending up with a byte order mark before your actual content.

You can avoid this by calling new UTF8Encoding(false) instead of using Encoding.UTF8. Here's a short program to demonstrate the difference:

using System;
using System.Text;
using System.IO;

class Test    
{
    static void Main()
    {
        Encoding enc = new UTF8Encoding(false); // Prints 1 1
        // Encoding enc = Encoding.UTF8; // Prints 1 4
        string content = "x";
        Console.WriteLine(enc.GetByteCount("x"));
        MemoryStream ms = new MemoryStream();
        StreamWriter sw = new StreamWriter(ms, enc);
        sw.Write(content);
        sw.Flush();
        Console.WriteLine(ms.Length);
    }

}