C# 如何使用 .NET HttpWebRequest API 从响应中读取 HTTP 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2371835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:51:28  来源:igfitidea点击:

How to read HTTP header from response using .NET HttpWebRequest API?

c#twitteroauthhttpwebresponse

提问by Ryan Alford

My app currently uses OAuth to communicate with the Twitter API. Back in December, Twitter upped the rate limit for OAuth to 350 requests per hour. However, I am not seeing this. I am still getting 150 from the account/rate_limit_statusmethod.

我的应用程序目前使用 OAuth 与 Twitter API 进行通信。早在 12 月,Twitter 就将 OAuth 的速率限制提高到每小时 350 个请求。但是,我没有看到这一点。我仍然从account/rate_limit_status方法中得到 150 。

I was told that I needed to use the X-RateLimit-LimitHTTP header to get the new rate limit. However, in my code, I do not see that header.

有人告诉我,我需要使用X-RateLimit-LimitHTTP 标头来获取新的速率限制。但是,在我的代码中,我没有看到该标题。

Here is my code...

这是我的代码...

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newURL);
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/x-www-form-urlencoded";

using (WebResponse response = request.GetResponse())
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        responseString = reader.ReadToEnd();
    }
}

If I inspect the response, I can see that it has a property for Headers, and that there are 16 headers. However, I do not have X-RateLimit-Limitin the list.

如果我检查response,我可以看到它有一个属性 for Headers,并且有 16 个标题。但是,我没有X-RateLimit-Limit在列表中。

Image
(source: yfrog.com)

图片
(来源:yfrog.com

Any idea what I am doing wrong?

知道我做错了什么吗?

采纳答案by Craig Stuntz

Look at the raw response text (e.g., with Fiddler). If the header isn't there, no amount of C# code is going to make it appear. :) From what you've shown, it seems the header isn't in the response.

查看原始响应文本(例如,使用 Fiddler)。如果标题不存在,则没有多少 C# 代码会使其出现。:) 从您所展示的内容来看,标题似乎不在响应中。

Update: When I go to: http://twitter.com/account/rate_limit_status.xmlthere is no X-RateLimit-Limitheader. But when I go to http://twitter.com/statuses/public_timeline.xml, it's there. So I think you just need to use a different method.

更新:当我去:http: //twitter.com/account/rate_limit_status.xml没有X-RateLimit-Limit标题。但是当我访问http://twitter.com/statuses/public_timeline.xml 时,它就在那里。所以我认为你只需要使用不同的方法。

It still says 150, though!

不过,它仍然显示 150!

回答by Russ Clarke

You should simple be able to use:

您应该可以简单地使用:

using (WebResponse response = request.GetResponse())
{
  string limit = response.Headers["X-RateLimit-Limit"];
  ...
}

If that doesn't work as expected, you can do a watch on response.Headers and see what's in there.

如果这没有按预期工作,您可以查看 response.Headers 并查看其中的内容。