WebRequest-防止重定向 [英] WebRequest - Prevent redirection
问题描述
我正在使用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>
推荐答案
You can use HttpWebRequest
’s AllowAutoRedirect
property:
…
var req = (HttpWebRequest)WebRequest.Create(URI);
req.AllowAutoRedirect = false;
…
这篇关于WebRequest-防止重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!