Skip to main content
 首页 » 编程设计

c#之System.Net.WebException:服务器违反了协议(protocol)

2024年02月05日27java哥

我有以下代码进行调用,然后返回 xml:

private string Send(string url) 
{ 
    try 
    { 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
 
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
        { 
            using (Stream stream = response.GetResponseStream()) 
            { 
                using (StreamReader reader = new StreamReader(stream)) 
                { 
                    return reader.ReadToEnd(); 
                } 
            } 
        } 
    } 
    catch (WebException ex) 
    { 
        var _status = ex.Status.ToString(); 
        if (ex.Status == WebExceptionStatus.ProtocolError) 
        { 
            _status = ((HttpWebResponse)ex.Response).StatusCode.ToString(); 
        } 
        Trace.WriteLine(_status.ToString()); 
    } 
 
    return "error"; 
} 

大多数时候(不总是)我得到

System.Net.WebException: The server committed a protocol violation.

Section=ResponseStatusLine at System.Net.HttpWebRequest.GetResponse()

抛出异常。

我已将其直接添加到我的 App.config 中 <configuration>部分:

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

但我继续收到错误。

请您参考如下方法:

设置

request.KeepAlive = false; 

http://www.webmonkeys.org.uk/2012/09/c-the-server-committed-a-protocol-violation-sectionresponsestatusline/#comment-60

此外,您粘贴的 useUnsafeHeaderParsing 配置值将其设置为 false,如果您试图解决此问题,则应将其设置为 true。