Here's the code I'm using:
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);
// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
return result;
When I'm running this, I'm always getting 500 internal server error.
What am I doing wrong?
Take care of the Content-Type you are using :
Sources :
RFC4627
Other post
I finally invoked in sync mode by including the .Result
Further to Sean's post, it isn't necessary to nest the using statements. By
using
the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call theFlush()
andClose()
methods:If you need to call is asynchronously then use
The way I do it and is working is:
I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest
Hope it helps.