c# - 使用 HtmlAgilityPack 下载网页时违反 HTTP 协议(protocol)

标签 c# .net html-agility-pack system.net.webexception

我正在尝试解析来自 www.mediafire.com 的下载页面,但当我尝试将页面加载到Html文档:

The server committed a protocol violation. Section=ResponseStatusLine

这是我的代码:

HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();

HtmlAgilityPack.HtmlDocument doc = null;

string url = www.mediafire.com/?abcdefghijkl //There are many different links

try
{
    doc = web.Load(url); //From 30 links, usually only 10 load properly
}

catch (WebException)
{

}

有什么想法为什么 30 个链接中只有 10 个有效(链接每次都会更改,因为我的程序是一个“搜索引擎”)以及我如何解决该问题?

当我在浏览器中加载这些网站时,一切正常。


我尝试将以下行添加到我的 app.config 中,但这也没有帮助

<system.net>
    <settings>
        <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>

最佳答案

这与 Html Agility Pack 没有直接关系,而是与底层 HTTP/socket 层相关。此错误意味着服务器没有发回正确的 HTTP 状态行。

状态行在 HTTP RFC 中定义,可在此处获取:http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

我引用:

The first line of a Response message is the Status-Line, consisting of the protocol version followed by a numeric status code and its associated textual phrase, with each element separated by SP characters. No CR or LF is allowed except in the final CRLF sequence.

   Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

您可以添加带有完整十六进制报告的套接字跟踪来检查这一点:

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net.Sockets" tracemode="includehex">
                <listeners>
                    <add name="System.Net.Sockets" type="System.Diagnostics.TextWriterTraceListener" initializeData="SocketTrace.log" />
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net.Sockets" value="Verbose"/>
        </switches>
        <trace autoflush="true" />
    </system.diagnostics>
</configuration>

这将在当前执行目录中创建一个 SocketTrace.log 文件。看看那里,违反协议(protocol)的行为应该是可见的。如果不是太大,您可以将其发布在这里:-)

不幸的是,如果您不拥有服务器,则您无能为力(如果您已经添加了 useUnsafeHeaderParsing 设置,这很好),但在这些情况下会优雅地失败。

关于c# - 使用 HtmlAgilityPack 下载网页时违反 HTTP 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4656723/

相关文章:

c# - IOC 容器可以替代 CreateInstance 反射代码吗?

c# - HTML 敏捷解析

c# - HTMLagilitypack 没有删除所有 html 标签 我怎样才能有效地解决这个问题?

c# - HtmlAgilityPack 是否能够在其 XPATH 选择器中使用正则表达式?

c# - Microsoft Band 异常 : 0xA0D4000A

c# - C#程序的自动更新

c# - ASP.NET CORE 没有 app.UseEndpoints() 方法

c# - 两个相等的 IPv6 IPAddress 实例返回不同的 GetHashCode 结果

.net - Double.ToString ("C")返回不正确的货币符号

c# - 返回任务的命名方法的公认模式是什么?