How to post JSON to a server using C#?
The way I do it and is working is:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");httpWebRequest.ContentType = "application/json";httpWebRequest.Method = "POST";using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){ string json = "{\"user\":\"test\"," + "\"password\":\"bla\"}"; streamWriter.Write(json);}var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();using (var streamReader = new StreamReader(httpResponse.GetResponseStream())){ var result = streamReader.ReadToEnd();}
I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest
Hope it helps.
Ademar's solution can be improved by leveraging JavaScriptSerializer
's Serialize
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 calling Flush
and Close
.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");httpWebRequest.ContentType = "application/json";httpWebRequest.Method = "POST";using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){ string json = new JavaScriptSerializer().Serialize(new { user = "Foo", password = "Baz" }); streamWriter.Write(json);}var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();using (var streamReader = new StreamReader(httpResponse.GetResponseStream())){ var result = streamReader.ReadToEnd();}
The HttpClient
type is a newer implementation than the WebClient
and HttpWebRequest
.
You can simply use the following lines.
string myJson = "{'Username': 'myusername','Password':'pass'}";using (var client = new HttpClient()){ var response = await client.PostAsync( "http://yourUrl", new StringContent(myJson, Encoding.UTF8, "application/json"));}
When you need your HttpClient
more than once it's recommended to only create one instance and reuse it or use the new HttpClientFactory
.