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

只愿长相守 提交于 2019-12-30 04:31:05

问题


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_status method.

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

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-Limit in the list.


(source: yfrog.com)

Any idea what I am doing wrong?


回答1:


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.

Update: When I go to: http://twitter.com/account/rate_limit_status.xml there is no X-RateLimit-Limit header. 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.

It still says 150, though!




回答2:


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.



来源:https://stackoverflow.com/questions/2371835/how-to-read-http-header-from-response-using-net-httpwebrequest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!