更新时间:2022-03-06 05:55:26
请阅读此答案结尾的警告,以了解为什么使用HTTP GET
Please read the caveats at the end of this answer as to why HTTP GET requests with bodies are, in general, not advised.
如果您是使用.NET Core ,即标准 HttpClient
可以立即使用。例如,要发送带有JSON正文的GET请求:
If you are using .NET Core, the standard HttpClient
can do this out-of-the-box. For example, to send a GET request with a JSON body:
HttpClient client = ...
...
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
.NET 框架不支持此功能-the-box(如果您尝试上面的代码,您将收到 ProtocolViolationException
)。幸运的是,Microsoft提供了 System.Net.Http.WinHttpHandler 程序包确实支持该功能-只需安装并使用它即可代替默认的 HttpClient 实例时,httpclienthandler rel = noreferrer> HttpClientHandler
:
.NET Framework doesn't support this out-of-the-box (you will receive a ProtocolViolationException
if you try the above code). Thankfully Microsoft has provided the System.Net.Http.WinHttpHandler package that does support the functionality - simply install and use it instead of the default HttpClientHandler
when constructing your HttpClient
instances:
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
<rest of code as above>
参考: https://github.com/dotnet/corefx/issues/28135#issuecomment-467261945
注意事项: