I have researched a lot and many people mentioned it is not possible to Get request with a body. I managed to get a response from it using Postman. Now I want to write in my code but I have no idea how to do so. I need to get the response but for this URL to work, I will need to include the body. Does anyone have any idea how to include the body using C# code?
This is my current code but there is an error ->
System.PlatformNotSupportedException: 'WinHttpHandler is only supported on .NET Framework and .NET Core runtimes on Windows. It is not supported for Windows Store Applications (UWP) or Unix platforms.'
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("my url"),
Content = new StringContent("my json body content", Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
string text = responsebody.ToString();
string[] str = text.Split(new[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
string result = str[10];
labelTxt.Text = result;
You're using the Windows-specific WinHttpHandler
type in your code, which you don't need to do as you're not customising it, which is what's causing the exception.
If you change your code to the below, it should work for any platform on .NET Core:
var client = new HttpClient(); // Changed to use the default HttpClient constructor
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("my url"),
Content = new StringContent("my json body content", Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
string text = responsebody.ToString();
string[] str = text.Split(new[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
string result = str[10];
labelTxt.Text = result;