The server committed a protocol violation. Section=ResponseStatusLine

July 18, 2011 No Comments by Jeff Cheung

I’ve reused my HttpWebRequest library over and over before when automating posts to webservers, webservices, etc. I’ve come across this error, “The server committed a protocol violation. Section=ResponseStatusLine”, many times before. In the past frameworks (1.1, specifically), all I had to do was add
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true"/>
</settings>
</system.net>
to the web.config or app.config, depending on my application. There were some instances where I had to set the KeepAlive property to false. Recently, in a project of mine, none of these things worked. The only thing that seemed to have any effect on the error was setting the ProtocolVersion back to 1.0. Weird…

public static string Post(CookieContainer incookies, out CookieContainer outcookies, string Url, string data, string Referer, out string outUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.CookieContainer = incookies;
request.Method = WebRequestMethods.Http.Post;
request.Referer = Referer;
request.ContentType = "application/x-www-form-urlencoded";
request.ProtocolVersion = HttpVersion.Version10;
request.ContentLength = data.Length;
request.KeepAlive = false;
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string output = reader.ReadToEnd();
outUrl = response.ResponseUri.ToString();
response.Close();
request = null;
response = null;
outcookies = incookies;
return output;
}

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>