Home > Net >  Send a POST request to an endpoint with C# and HttpWebRequest
Send a POST request to an endpoint with C# and HttpWebRequest

Time:09-27

It is no problem for me to send a GET-Request to an endpoint with the following code (of course with the GET-Method), but I am not able to do a POST-Request. Can somebody explain, what I have to do in order to be able to POST the exemplary JSON-Body?

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;


namespace RestTesting

{
    class Program
    {
        static void Main(string[] args)
        {

            string url;
            url = "https://server.APIEndpoint/REST/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";
            request.KeepAlive = true;

            request.Credentials = CredentialCache.DefaultCredentials;

            Console.WriteLine("Request: {0} \"{1}\" ...", request.Method, request.RequestUri);
            Console.WriteLine(request.Headers);
            Console.WriteLine(request.ContentLength);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(String.Format("Response: HTTP/{0} {1} ({1:d})\n", response.ProtocolVersion, response.StatusCode));

                Console.WriteLine(response.Headers);
                string responseText;

                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    responseText = reader.ReadToEnd();
                }

                Console.WriteLine(response.ContentType);

                if (response.ContentType.StartsWith("application/json"))
                {
                    JObject json = (JObject)JObject.Parse(responseText);
                    Console.WriteLine(json.ToString());
                }

            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }

            Console.WriteLine("Press enter to close...");
            Console.ReadLine();

        }
    }
}

And here is a JSON-Body:

{
"reference": "Test", 
"info": "additionalInfo", 
"ID": null, 
"confidential": false,
}

The issue is: System.Net.WebException: The remote server returned an error: (404) Not Found. at System.Net.HttpWebRequest.GetResponse() at RestTesting.Program.Main(String[] args)

That error occurs when I try to post the JSON-Body like below (after the WebRequest.Create Method):

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string data = @"{
        "reference": "Test", 
        "info": "additionalInfo", 
        "ID": null, 
        "confidential": false,  
    }";
    streamWriter.Write(data);
}

Thank you very much in advance!

CodePudding user response:

Solution: I just forgot a comma in my code in the JSON-Body.

  • Related