How to send HTTP POST request in .NET (C#)? Problem with WebRequest and getting response
Hello everyone! I'm a beginner in C# and trying to send a POST request to an external API to pass JSON data and get a response. I've come across many examples, but they are either outdated (with WebRequest) or too complicated for me.
Here's my current code that I've put together, but it doesn't work — I get the error "The remote server returned an error: (400) Bad Request" or it just hangs:
```csharp
using System.Net;
var request = (HttpWebRequest)WebRequest.Create("https://example.com/api/data");
request.Method = "POST";
request.ContentType = "application/json";
string json = "{\"name\":\"test\",\"value\":123}";
byte[] bytes = Encoding.UTF8.GetBytes(json);
request.ContentLength = bytes.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
```