我正在使用API进行一些集成工作,当你达到每日限额时,它会返回一个HttpStatusCode 429。但是,Web响应对象中的Enum HttpStatusCode不包含此代码。
有人可以告诉我如何检查此响应代码吗?
以下是一些显示我想要完成的内容的代码:
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;
}
答案 0 :(得分:0)
我有同样的问题,您可以阅读响应,然后查找429或过多的请求字符串:
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 :(得分:0)
我遇到了同样的问题,在寻找解决方案时我意识到了一些事情。
WebExceptionStatus
enum
不等同于您调用的API返回的http状态代码。相反,它是一个可能的错误枚举,可能在http调用期间发生。WebExceptionStatus
错误代码是WebExceptionStatus.ProtocolError
,也就是数字7(整数)。WebExceptionStatus.Status
是否为WebExceptionStatus.ProtocolError
。然后,您可以从WebExceptionStatus.Response
获得真实的响应并阅读其内容。这是一个示例:
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
}