目前要向 API 接口发送参数化的 GET 请求,我正在编写以下代码:
Currently to send a parameterized GET request to an API interface I am writing the following code:
api/master/city/filter?cityid=1&citycode='ny'但我看到 URL 长度有 2,083 个字符的限制.
But I see that there is a limit on the URL length of 2,083 characters.
为了避免这种情况,我想在 GET 请求的内容正文中以 json 格式发送参数.
To avoid this I would like to send the parameters in json format in the content body for a GET request.
但是,我发现 HttpClient 的所有 Get 方法都不允许发送内容正文.对于 POST,我可以看到 HttpClient 中有一个名为 PostAsync 的方法,它允许使用内容正文.
However, I see that none of the Get methods for the HttpClient allow for a content body to be sent. For the POST I could see there is a method within HttpClient named PostAsync that allows for a content body.
有没有办法为不在 URL 中的 GET 请求发送参数以避免 URL 长度限制?
Is there a way to send parameters for a GET request not in the URL in order to avoid the URL length limit?
推荐答案请阅读此答案末尾的警告,了解为什么通常不建议使用带有正文的 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:
.NET Framework 不支持这种现成的(如果您尝试上述代码,您将收到 ProtocolViolationException).幸运的是,微软提供了 System.Net.Http.WinHttpHandler 包确实支持该功能 - 只需安装并使用它而不是默认的 HttpClientHandler 在构建你的 HttpClient 实例时:
.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>参考:github/dotnet/runtime/issues/25485#issuecomment-467261945
注意事项:
- 带有正文的 HTTP GET 是一种有点非常规的构造,属于 HTTP 规范的灰色区域 - 最终结果是许多较旧的软件要么根本无法处理此类请求,要么会明确拒绝它,因为它们相信它是畸形的.您需要非常确保您尝试向其发送此类请求的端点确实支持它,否则您最多会得到一个 HTTP 错误代码;在最坏的情况下,尸体将被无声地丢弃.这可能会导致一些令人头疼的调试!
- 缓存代理服务器,尤其是较旧的代理服务器,可能仅根据 URL 缓存 GET 请求,因为它们不希望存在正文.这可能导致永远缓存最近的请求(这会破坏您的软件),或者唯一缓存的请求是最近发出的请求(这将阻止缓存按预期工作).同样,这可能很难弄清楚.
更多推荐
如何使用 HttpClient 在 GET 请求正文中发送内容?
发布评论