WebRequest-防止重定向 [英] WebRequest - Prevent redirection

查看:206
本文介绍了WebRequest-防止重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WebRequest来读取HTML站点.服务器似乎正在重定向我的请求.

I am using a WebRequest to read an HTML site. The server seems to be redirecting my request.

我的代码类似于以下内容:

My Code is similar to the following:

    String URI = "http://www.foo.com/bar/index.html"
    WebRequest req = WebRequest.Create(URI);
    WebResponse resp = req.GetResponse();
    StreamReader sr = new StreamReader(resp.GetResponseStream());
    String returnedContent = sr.ReadToEnd();

当我检查returnedContent的内容时,它包含重定向之类的内容,例如"http://www.foo.com/FOO_BAR/index.html".我确定我所请求的URL存在,因为它是收到的响应的一部分(作为IFrame).

When I check the content of the returnedContent it contains the content from a redirection like "http://www.foo.com/FOO_BAR/index.html". I am sure my requested URL exists since it is part of the recieved response (as an IFrame).

是否有一种方法可以防止WebResponse重定向并获取所请求的url的内容?

Is there a way to prevent the WebResponse to be redirected and get the content of the requested url?

更新

设置req.AllowAutoRedirect = false会导致出现302 Found状态代码,但不会传递实际内容.

Setting req.AllowAutoRedirect = false leads to a 302 Found state code, but does not deliver the acutal content.

更多详细信息: 我请求的网址是http://www.foo.com/bar/index.html我收到的内容位于http://www.foo.com/FOO_BAR/index.html

Some more details: My requested url was http://www.foo.com/bar/index.html the content I receive is located in http://www.foo.com/FOO_BAR/index.html

响应类似于以下内容:

<body>
    <div>
        <iframe src="/foo/index.html"></iframe>
    </div>
</body>

推荐答案

您可以使用HttpWebRequest

You can use HttpWebRequest’s AllowAutoRedirect property:

…
var req = (HttpWebRequest)WebRequest.Create(URI);
req.AllowAutoRedirect = false;
…

这篇关于WebRequest-防止重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆