160-send-json-text-over-http-in-c

Sending data over http in C# is easy if we use HttpWebRequest and WebResponse classes. Once when we have our data in json format ready for sending, we can send json text over http in C#. We need to make an object of System.Net.HttpWebRequest class by casting the same class. It might look a little peculiar.

var httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(“http://www.yoursite.com/something.php”);

Next step is to define content type and method:

httpWebRequest.ContentType = “text/json”;
httpWebRequest.Method = “POST”;

Final step is to make an StreamWriter object and use it for http protocol data serialization. Let’s presume that our data are in str_my_json1 variable that was filled with data before. We also need to include IO namespace.

using System.IO;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{

streamWriter.Write(str_my_json1);
streamWriter.Flush();
streamWriter.Close();

}

When data are sent, good practice is to check response. For that purpose we need object of an System.Net.WebResponse class. This time we use normal cast.

var httpResponse = (System.Net.WebResponse)httpWebRequest.GetResponse();

Then we need one StreamReader object to read responses.
string str_response;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{

var result = streamReader.ReadToEnd();
str_response = result.ToString();

}
label3.Text = str_response;
And that’s it!

Whole code is:

var httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(“http://www.yoursite.com/something.php”);
httpWebRequest.ContentType = “text/json”;
httpWebRequest.Method = “POST”;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{

streamWriter.Write(str_my_json1);
streamWriter.Flush();
streamWriter.Close();

}
var httpResponse = (System.Net.WebResponse)httpWebRequest.GetResponse();
string str_response;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{

var result = streamReader.ReadToEnd();
str_response = result.ToString();

}
label3.Text = str_response;

External links:

Send json text over http in C# in stackoverflow
Send json text over http in C# in example-code

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*