How to post JSON to a server using C#?

ID : 10038

viewed : 28

Tags : c#jsonposthttpwebrequestc#

Top 5 Answer for How to post JSON to a server using C#?

vote vote

96

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.

vote vote

85

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(); } 
vote vote

73

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.

vote vote

66

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 the Flush() and Close() methods:

var request = (HttpWebRequest)WebRequest.Create("http://url"); request.ContentType = "application/json"; request.Method = "POST";  using (var streamWriter = new StreamWriter(request.GetRequestStream())) {     string json = new JavaScriptSerializer().Serialize(new                 {                     user = "Foo",                     password = "Baz"                 });      streamWriter.Write(json); }  var response = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) {         var result = streamReader.ReadToEnd(); } 
vote vote

51

If you need to call is asynchronously then use

var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest;             request.Method = "POST";             request.ContentType = "text/json";             request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);  private void GetRequestStreamCallback(IAsyncResult asynchronousResult)     {         HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;         // End the stream request operation          Stream postStream = request.EndGetRequestStream(asynchronousResult);           // Create the post data         string postData = JsonConvert.SerializeObject(edit).ToString();          byte[] byteArray = Encoding.UTF8.GetBytes(postData);           postStream.Write(byteArray, 0, byteArray.Length);         postStream.Close();          //Start the web request         request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);     }      void GetResponceStreamCallback(IAsyncResult callbackResult)     {         HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);         using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))         {             string result = httpWebStreamReader.ReadToEnd();             stat.Text = result;         }      } 

Top 3 video Explaining How to post JSON to a server using C#?

Related QUESTION?