我正在使用 WebRequest
读取 HTML 站点。服务器似乎正在重定向我的请求。
我的代码类似于以下内容:
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)。
有没有办法阻止 WebResponse
被重定向并获取请求的 url 的内容?
更新
设置 req.AllowAutoRedirect = false
会导致 302 Found
状态代码,但不会传送实际内容。
更多细节:
我请求的 url 是 http://www.foo.com/bar/index.html
我收到的内容位于 http://www.foo.com/FOO_BAR/index。 html
响应看起来类似于:
<body>
<div>
<iframe src="/foo/index.html"></iframe>
</div>
</body>
最佳答案
您可以使用HttpWebRequest
的AllowAutoRedirect
property :
…
var req = (HttpWebRequest)WebRequest.Create(URI);
req.AllowAutoRedirect = false;
…
关于c# - WebRequest - 防止重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012384/