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!
2 Answers 2
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.
-
Than kyou. For serveral reasons, I have to use the webrequst. Can you show me how its done using this old api? :)Jay– Jay2021年03月30日 10:42:39 +00:00Commented Mar 30, 2021 at 10:42
-
is httpclient from system..net.http? cause that one doesnt have postasjsonasync for me...Jay– Jay2021年03月30日 10:48:27 +00:00Commented Mar 30, 2021 at 10:48
-
1See stackoverflow.com/questions/19158378/…. It's an extension method in the
Microsoft.AspNet.WebApi.Client
NuGet package.CodeCaster– CodeCaster2021年03月30日 10:49:25 +00:00Commented Mar 30, 2021 at 10:49 -
1Then you need to consult said API's documentation to check why it won't accept that payload.CodeCaster– CodeCaster2021年03月30日 11:02:30 +00:00Commented Mar 30, 2021 at 11:02
-
1Thank 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!Jay– Jay2021年03月30日 12:01:15 +00:00Commented Mar 30, 2021 at 12:01
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.
httpRequest.ContentType= "application/json";
stackoverflow.com/questions/9145667/…await Task.Run(() => JsonConvert.SerializeObject(payload))
"? Really?StringContent
,ReadAsStringAsync()
? ThePostAsJsonAsync()
extension method exists for over six years already.