How to post JSON to the server?

[Originally Posted By]: http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server

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);
    streamWriter.Flush();
    streamWriter.Close();
}

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.

shareedit

 

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

}
shareedit
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s