首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpWebResponse状态代码429

HttpWebResponse状态代码429
EN

Stack Overflow用户
提问于 2017-04-12 23:32:10
回答 2查看 2.3K关注 0票数 1

我正在做一些集成工作,当你达到每日限制时,它会返回一个HttpStatusCode 429。但是,web响应对象中的枚举HttpStatusCode不包含此代码。

有人能告诉我如何检查这个响应码吗?

下面是一些代码,展示了我想要完成的任务:

代码语言:javascript
复制
try
{
  //do something
}
catch (WebException webExp)
{
     var response = (HttpWebResponse) webExp.Response;

     //here I want to check status code for too many requests but it is not   in the enum.
    if (response.StatusCode == HttpStatusCode.TooManyRequests) throw webExp;
}
EN

回答 2

Stack Overflow用户

发布于 2020-08-01 06:51:38

我也有同样的问题,在我寻找解决方案的时候,我意识到了一些事情。

  • WebExceptionStatus enum不等同于您调用的接口返回的http状态码。
  • 当你的接口收到错误(400到599)时,返回的WebExceptionStatus错误码是WebExceptionStatus.ProtocolError,也就是7号为int。
  • 当你需要获取接口返回的响应体或真正的http状态码时,首先需要检查WebExceptionStatus.Status是否为WebExceptionStatus.ProtocolError。然后,您可以从WebExceptionStatus.Response获得真正的响应,并阅读其内容。

这是一个示例:

代码语言:javascript
复制
try
{
    ...
}
catch (WebException webException)
{
    if (webException.Status == WebExceptionStatus.ProtocolError)
    {
        var httpResponse = (HttpWebResponse)webException.Response;
        var responseText = "";
        using (var content = new StreamReader(httpResponse.GetResponseStream()))
        {
            responseText = content.ReadToEnd(); // Get response body as text
        }
        int statusCode = (int)httpResponse.StatusCode; // Get the status code (429 error code will be here)
        return statusCode;
    }

    // Handle other webException.Status errors
}
票数 0
EN

Stack Overflow用户

发布于 2017-06-08 22:55:12

我也有同样的问题,你可以读取响应,然后查找429或太多的请求字符串:

代码语言:javascript
复制
string responseStr = "";
Stream responseStream = webEx.Response.GetResponseStream();
if (responseStream != null)
{
    using (StreamReader sr = new StreamReader(responseStream))
    {
       responseStr = sr.ReadToEnd();
    }
}

if (responseStr.Contains("429") || responseStr.Contains("Too many requests"))
Console.WriteLine("Is 429 WebException ");
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43373871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档