我正在做一些集成工作,当你达到每日限制时,它会返回一个HttpStatusCode 429。但是,web响应对象中的枚举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;
}发布于 2020-08-01 06:51:38
我也有同样的问题,在我寻找解决方案的时候,我意识到了一些事情。
WebExceptionStatus enum不等同于您调用的接口返回的http状态码。WebExceptionStatus错误码是WebExceptionStatus.ProtocolError,也就是7号为int。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
}发布于 2017-06-08 22:55:12
我也有同样的问题,你可以读取响应,然后查找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 ");https://stackoverflow.com/questions/43373871
复制相似问题