为什么不允许HttpClient自动重定向?

3
我正在尝试使用不同的User-Agent爬取一些域名。我的爬虫工作正常,但当一个域名没有SSL证书且不安全时,就会出现问题,此时我使用HttpHandler并自己设置证书来跳过这个问题。
通过这种解决方案,我对所有这些域名都得到了301 ,这感觉像是我的AllowAutoRedirect为false,但实际上并非如此。我尝试将MaxAutomaticRedirections指定为5,但也没有起作用。
以下是我的代码:
public Task<int> Crawl(string userAgent, string url)
{
    var handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ServerCertificateCustomValidationCallback =
        (httpRequestMessage, cert, cetChain, policyErrors) =>
    {
        return true;
    };

    var httpClient = new HttpClient(handler);

    httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);


    var statusCode = (int)(await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, URL))).StatusCode;

    return statusCode;
}

你尝试过使用 HttpClientHandler.DangerousAcceptAnyServerCertificateValidator 替代 ClientCertificationOption.Manual 吗? - keenthinker
3
您可能想查看HttpClient即使AllowAutoRedirect = true也不重定向 - Heretic Monkey
1个回答

1

我尝试爬取的域名没有SSL证书,HttpClient被重定向到HTTP版本。我的猜测是HttpClient不知道它被重定向到哪里,所以就停止了。

通过爬取域名的HTTP版本,我的问题得到了解决,例如:http://example.com


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接