且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用HttpClient在GET请求的正文中发送内容?

更新时间: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

    注意事项:


    • HTTP GET with主体是某种有点非常规的构造,它落在HTTP规范的灰色区域内-最终结果是,许多较旧的软件要么根本无法处理这样的请求,要么因为认为格式不正确而将其明确拒绝。您需要非常确定要发送此类请求的端点是否支持该请求,否则充其量您将获得HTTP错误代码;在最坏的情况下,尸体将被无声丢弃。

    • 缓存代理服务器(尤其是较旧的代理服务器)可能仅基于URL缓存GET请求,因为它们不希望出现正文,这可能会导致一些麻烦的调试工作。 。这可能会导致永久存储最近的请求(这将破坏您的软件),或者导致缓存的唯一请求是最新发出的请求(这将阻止缓存按预期工作)。同样,弄清楚这可能非常痛苦。