0

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!

asked Mar 30, 2021 at 10:34
6
  • try change to httpRequest.ContentType= "application/json"; stackoverflow.com/questions/9145667/… Commented Mar 30, 2021 at 10:38
  • Usually in authorization headers, a bearer access token is supplied instead of an API key. Commented Mar 30, 2021 at 10:38
  • Does this answer your question? How to post JSON to a server using C#? Commented Mar 30, 2021 at 10:39
  • 1
    @Self holy sh*t there's a lot of bad code being heavily upvoted on this site. Look at the accepted answer on the second Q&A you link to. "await Task.Run(() => JsonConvert.SerializeObject(payload))"? Really? StringContent, ReadAsStringAsync()? The PostAsJsonAsync() extension method exists for over six years already. Commented Mar 30, 2021 at 10:42
  • 1
    @CodeCaster, Good catch. I just don't read most of the code. I can find dupe target without reading the question most of the time. I will try to give answers code a better look if theirs numbers is not too big. But a basic search query return too many possible dupe. Commented Mar 30, 2021 at 12:21

2 Answers 2

3

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.

answered Mar 30, 2021 at 10:39
8
  • Than kyou. For serveral reasons, I have to use the webrequst. Can you show me how its done using this old api? :) Commented Mar 30, 2021 at 10:42
  • is httpclient from system..net.http? cause that one doesnt have postasjsonasync for me... Commented Mar 30, 2021 at 10:48
  • 1
    See stackoverflow.com/questions/19158378/…. It's an extension method in the Microsoft.AspNet.WebApi.Client NuGet package. Commented Mar 30, 2021 at 10:49
  • 1
    Then you need to consult said API's documentation to check why it won't accept that payload. Commented Mar 30, 2021 at 11:02
  • 1
    Thank you. Working with postman fixed the issue. Appeeantly, the API checked for the input values if they are valid e.g: is this a valid email, is this a valid phone number, etc. That was the last issue I had. Thanks for ur help! Commented Mar 30, 2021 at 12:01
0

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.

answered Mar 30, 2021 at 11:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.