In the following samples, you can find out how to send a HTTP POST request with C#. I work a lot with JSON, so here I’ll show how to send a JSON string. Here we go!

In this sample, the server returns a JSON string structured like the class Response and I parse it in a dictionary to navigate its fields. Otherwise, if for example the server returns a simple string, this step is useless.

[Serializable]
public class Response
{
    public bool resultSuccess;
    public errorType errorType;
    public Response() { }
}

public Response sendPOST(string url, string json )
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        var res = new JavaScriptSerializer().Deserialize<Response>(result);
        return res;
    }
}

For using the JavaScriptSerializer, read here.

Advertisements