【发布时间】:2020-04-08 09:58:53
【问题描述】:
我进行了很多研究,很多人提到不可能通过身体获取请求。我设法使用邮递员从它那里得到了回应。现在我想写我的代码,但我不知道该怎么做。我需要得到响应,但要让这个 url 起作用,我需要包含正文。有谁知道如何使用 C# 代码包含正文?
这是我当前的代码,但有一个错误 -> 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;
【问题讨论】:
-
只需将代码更改为
var client = new HttpClient();- 如果您不自定义WinHttpHandler,那么如果您使用 HttpClient 的默认构造函数,它将为您的平台选择适当的内部处理程序。 -
使用HttpClient docs.microsoft.com/en-us/dotnet/api/…
-
您可能应该使用
HttpClientHandler而不是Windows 特定的WinHttpHandler。尽管您似乎没有对处理程序做任何事情,所以只需按照@MartinCostello 的建议使用new HttpClient() -
这通常是个坏主意。它“有效”,但违反 HTTP 规范对 GET 请求的正文赋予任何含义。 stackoverflow.com/questions/978061/http-get-with-request-body
-
@MartinCostello 嗨!在将我的代码更改为您提到的内容后,它起作用了。谢谢:)
标签: c# api httpclient