How to post JSON to the server?

[Originally Posted By]:

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\"," +


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:

Hope it helps.



If you need to call is asynchronously then use

var request = HttpWebRequest.Create("" + 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);

    //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;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s