当前要将参数化的GET请求发送到API接口,我正在编写以下代码:
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.
为避免这种情况,我想在JSON格式的内容正文中发送GET请求的参数。
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.
是否有一种方法可以为GET请求发送参数?为了避免URL长度限制而使用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 框架不支持此功能-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>参考: github/dotnet/corefx/issues/28135#issuecomment-467261945
注意事项:
- HTTP GET with主体是某种有点非常规的构造,它落在HTTP规范的灰色区域内-最终结果是,许多较旧的软件要么根本无法处理这样的请求,要么因为认为格式不正确而将其明确拒绝。您需要非常确定要发送此类请求的端点是否支持该请求,否则充其量您将获得HTTP错误代码;在最坏的情况下,尸体将被无声丢弃。
- 缓存代理服务器(尤其是较旧的代理服务器)可能仅基于URL缓存GET请求,因为它们不希望出现正文,这可能会导致一些麻烦的调试工作。 。这可能会导致永久存储最近的请求(这将破坏您的软件),或者导致缓存的唯一请求是最新发出的请求(这将阻止缓存按预期工作)。同样,弄清楚这可能非常痛苦。
更多推荐
如何使用HttpClient在GET请求的正文中发送内容?
发布评论