Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 487
F8R Avatar asked Jun 12 '11 23:06

F8R


Video Answer


1 Answers

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();
    }
}
like image 195
GSerjo Avatar answered Oct 29 '22 09:10

GSerjo