如何忽略401并继续阅读Feed

时间:2015-05-01 18:31:27

标签: c# .net httpwebrequest webrequest system.net.httpwebrequest

我得到了一个json feed。

无需任何用户名或密码即可访问。

可以从Google Chrome浏览器中看到。

在谷歌Chrome开发者工具中,它还说状态401, 但仍然能够读取数据。

然后我尝试使用C#web请求或webclient,我得到401并抛出,不再能够继续。

Chrome是如何做到的?我该怎么办?

我的C#代码:

WebRequest request = WebRequest.Create(url);
request.UseDefaultCredentials = true;
request.Method = WebRequestMethods.Http.Get;
((HttpWebRequest)request).UserAgent = userAgent;
request.Timeout = timeOut;
((HttpWebRequest)request).Accept = "application/json";
response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);

1 个答案:

答案 0 :(得分:0)

您可以“捕获”HttpWebRequest抛出的401异常,并使用以下代码从WebException中读取内容:

        try {
            // your code above
        }
        catch(Exception oEx)
        {
            if(oEx.GetType() == typeof(WebException))
            {
                HttpWebResponse wr = ((WebException)oEx).Response as HttpWebResponse;
                Stream dataStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
                string str = reader.ReadToEnd(); // str will contain the body of the HTTP 401 response
                reader.Close();
            }
        }