gpt4 book ai didi

c# - 如何为 Webclient 开启自动重定向

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:53 28 4
gpt4 key购买 nike

我有这个代码:

class CustomWebclient: WebClient
{
[System.Security.SecuritySafeCritical]
public CustomWebclient(): base()
{
}
public CookieContainer cookieContainer = new CookieContainer();


protected override WebRequest GetWebRequest(Uri myAddress)
{
WebRequest request = base.GetWebRequest(myAddress);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookieContainer;
(request as HttpWebRequest).AllowAutoRedirect = true;
}
return request;
}
}

当我加载页面 example.com 时,我得到:

Server: nginx
Date: Fri, 23 Aug 2013 05:24:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
location: /examplePage

但我的 CustomWebclient 不遵循重定向。为什么?如何修复它?

可能是因为“location”是小写所以没用。

最佳答案

您的代码在我的测试下运行良好。

当提供适当的 cookie 时,我的测试站点 weibo.com 将通过 HTTP 302 强制重定向。

关闭自动重定向,响应头是

Transfer-Encoding: chunked
Connection: close
Pramga: no-cache
DPOOL_HEADER: dagda24
Cache-Control: no-cache, must-revalidate
Content-Type: text/html
Date: Thu, 13 Mar 2014 15:07:53 GMT
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Thu, 13 Mar 2014 15:07:53 GMT
Location: /u/2398332747/home?wvr=5
Server: nginx

而且网页没有明显重定向。

启用自动重定向后,响应 header 是,

Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Pragma: no-cache
DPOOL_HEADER: balor165
Cache-Control: no-cache, must-revalidate
Content-Type: text/html; charset=utf-8
Date: Thu, 13 Mar 2014 15:13:26 GMT
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Server: nginx

网页内容验证请求被重定向。

我确实注意到 Location header 的第一个字母是大写的。这个没有测试header格式是否相关。

编辑:

最后,example.com 已经过测试,但在我的环境下它根本不会触发重定向。这就是我选择 weibo.com 作为备选方案的原因。

编辑:

我对此做了更多研究,根据 RFC 2616, header 不区分大小写。你的代码对我来说很好,仍然不知道为什么会出错。希望其他人提供线索。

关于c# - 如何为 Webclient 开启自动重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394761/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com