简体   繁体   中英

HttpWebRequest throws System.Net.WebException Section=ResponseStatusLine

I wrote a simple httpserver which i plan to interact with with HttpRequest/Response. The server gets the request and the parsing is fine but when i write back i get exception

System.Net.WebException: Der Server hat eine Protokollverletzung ausgeführt. Section=ResponseStatusLine
   bei System.Net.HttpWebRequest.GetResponse()

my servercode which writes back

TcpClient client = ...;
_stream = _client.GetStream();


// make sure "\r\n" is used as line ending, because it may be different on different OS
_output = new StreamWriter(_stream, Encoding.UTF8) { NewLine = "\r\n" };

length = 0;
code = 200;
message = "OK";
_output.WriteLine("HTTP/1.1 " + code + " " + message);
_output.WriteLine("Server: My Server");
_output.WriteLine("ContentLength: " + length);
_output.WriteLine("Connection: " + (_keepAlive ? "Keep-Alive" : "Close"));
_output.WriteLine();
_output.Flush();

client code

var request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080/foo");
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;

using (var res = request.GetResponse())   // throws here
{
}

any idea?

Update: as Jon mentioned first bug removed but still not working

alternate client code

using (var client = new TcpClient())
{
    client.Connect(new IPEndPoint(IPAddress.Loopback, 8080));
    using (var stream = client.GetStream())
    {
        var writer = new StreamWriter(stream);
        writer.WriteLine("GET /foo HTTP/1.1");
        writer.WriteLine("HOST:127.0.0.1");
        writer.WriteLine("Connection:Close");
        writer.WriteLine();
        writer.Flush();

        var response = new StreamReader(stream).ReadToEnd();
        foreach (var c in response)
        {
            if (char.IsControl(c))
                Console.Write("'{0}'" , (int)c);
            else
                Console.Write(c);
        }
    }
}

returns

HTTP/1.1 200 OK'13''10'Server: My custom Server'13''10'ContentLength: 0'13''10'Connection: Close'13''10''13''10'

Well this is very suspect to start with:

_output = new StreamWriter(_stream, Encoding.UTF8) { NewLine = "\n\r" };

I think you meant \\r\\n rather than \\n\\r .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM