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?
This option is not mentioned:
var data = Encoding.ASCII.GetBytes(json);
byte[] postBytes = Encoding.UTF8.GetBytes(json);
Use ASCII instead of UFT8
Some different and clean way to achieve this is by using HttpClient like this:
I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model [JsonObject] for your controller to get the values and do the conversion.
Request:
Model:
Server side:
The
HttpClient
type is the a newer implementation then theWebClient
andHttpWebRequest
.You can simply use the following lines.
When you need your HttpClient more then once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.
Ademar's solution can be improved by leveraging
JavaScriptSerializer
'sSerialize
method to provide implicit conversion of the object to JSON.Additionally, it is possible to leverage the
using
statement's default functionality in order to omit explicitly callingFlush
andClose
.