Post JSON data to web API using object in C#

33,602

Thanks to Mason! I wrote the code to POST the data to the web API using HttpWebRequest.

Main

static void Main(string[] args) 
{
    string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));

    Debug.Write(patientServiceResponse);
}

POST

private static string PostRequest(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "[  { \"ReferenceId\": \"a123\"  } ]";
            Debug.Write(json);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        try
        {
            using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
            {
                if (httpWebRequest.HaveResponse && response != null)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                using (var errorResponse = (HttpWebResponse)e.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string error = reader.ReadToEnd();
                        result = error;
                    }
                }

            }
        }

        return result;

    }
Share:
33,602
shockwave
Author by

shockwave

Updated on July 01, 2020

Comments

  • shockwave
    shockwave almost 4 years

    I was able to write the code to perform GET operation from a web API. But, I'm not able to POST. I think the problem is with the JSON object. I'm able to POST if the parameters are sent via URL but I'm unable to do so if it's a JSON Object. Eg: The POST requires me to send ModelID, CustomerID via URL and ReferenceString as a JSON object.

    Data to POST

    ModelID = 3345

    CustomerID =1V34858493

    ReferenceID is a JSON string[]

    [ { "ReferenceId": "a123" } ]

    Main

     static void Main(string[] args) 
        {
           // JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));
    
            Debug.Write(patientServiceResponse);
        }
    

    POST Request

    private static string PostRequest(string url)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json; charset=utf-8";
            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = "application/json; charset=utf-8";
            string sContentType = "application/json";
    
            JObject oJsonObject = new JObject();
    
            oJsonObject.Add("ReferenceId", "a123");
    
            HttpClient oHttpClient = new HttpClient();
            var oTaskPostAsync = oHttpClient.PostAsync(url, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));
    
            //return 
        }
    

    Can you please correct me where I'm going wrong.

  • William Han
    William Han almost 7 years
    I wasn't able to comment below. It is not a good idea to put too much inside the catch block. What if there is another exception inside it?