Jay
Jay

Reputation: 49

C# post json object using httpWebRequst

I need to post an object in this format:

POST https://link
{
  "country": "nld",
  "emailaddress": "[email protected]",
  "phone": "123",
  "notify_url": "https://asd.com"
}

I tried:

 var url = "URL";
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Accept = "*/*";
            httpRequest.Headers["Authorization"] = "Bearer " + apiKey;


            var postData = "country" + Uri.EscapeDataString("hello");
            postData += "emailaddress" + Uri.EscapeDataString("world");
            postData += "phone" + Uri.EscapeDataString("123");
            postData += "notify_url" + Uri.EscapeDataString("d3wq");
            var data = Encoding.ASCII.GetBytes(postData);

            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.ContentLength = data.Length;

            using (var stream = httpRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
 
            HttpWebResponse httpResponse = null;
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
            }
            catch (Exception e) { }

But the server returns a 400 bad request. I think the data is in invalid format.

How can i alter my code to put the data into correct format ?

Thank you!

Upvotes: 0

Views: 174

Answers (2)

H.Sarxha
H.Sarxha

Reputation: 174

Create object that you need to submit on your webrequest.

var xObject = new { xData = ... };

and after that use;

var newJsonData = JsonSerializer.Serialize(xObject);

newJsonData is a string as JSON format which you can post to your webrequest.

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151730

The example request you show, shows a JSON request body, yet you tell the server in your HttpWebRequest that the incoming content-type is going to be a form post. But then you don't issue a form post, you post one long string:

countryhelloemailaddressworldphone123 // and so on 

Don't use HttpWebRequest in 2021. It's a two decade old API that has more developer-friendly alternatives by now.

Use HttpClient instead, which has convenient (extension) methods for sending and receiving JSON:

var postModel = new
{ 
    country = "...", 
    emailaddress = "...", 
    ... 
}; 

var client = new HttpClient();

var response = await client.PostAsJsonAsync(postModel);

You need to install the Microsoft.AspNet.WebApi.Client NuGet package for that extension method.

If you insist you must use an HttpWebRequest, which I highly doubt, your question is answered in How to post JSON to a server using C#?, as that question and answer shows how to use that ancient API.

Upvotes: 3

Related Questions