HttpWebRequest, How to Send POST Data with Application/JSON Content-Type?

F8R picture F8R · Jun 13, 2011 · Viewed 48.6k times · Source
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

POST data was send (I check using Fiddler) returned from Yahoo :

{"error":{"code":-1003,"detail":"Unsupported Content Type Error","description":"Unsupported Content Type Error"},"code":-1003}

I'm writing Yahoo Messanger client that require application/json; charset=utf-8 as content type, and when I set :

request.ContentType = "application/json; charset=utf-8";

No POST data send, returned from Yahoo :

{"error":{"code":-1005,"detail":"Invalid Argument Error","description":"Invalid Argument Error"},"code":-1005}

UPDATE

I was try to send this 2 values via POST method : presenceState & status.

As stated in Yahoo Messager IM API supported content-type are application/json. And in my code, if I set content-type to application/json, HttpWebRequest didn't send those 2 values via POST.

Answer

GSerjo picture GSerjo · Aug 18, 2012

Take a look on following example

byte[] data = CreateData(value);
var requst = (HttpWebRequest) WebRequest.Create(uri);
requst.Method = "POST";
requst.ContentType = "application/json";
requst.ContentLength = data.Length;
using (Stream stream = requst.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

Where CreateData is

public static byte[] Create<T>(T value)
{
    var serializer = new DataContractJsonSerializer(typeof (T));
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, value);
        return stream.ToArray();
    }
}