使用.Net的SslStream在HTTPS请求Facebook的奇怪位置标头

时间:2016-10-31 10:43:24

标签: c# .net http ssl

我正在使用TCP套接字编写自己的HTTP客户端实现。

问题是它适用于我测试的所有地方,除了HTTPS以及#34; facebook.com&#34;。我的代码会在响应中返回HTTP标头:< / p>

Location: https://www.facebook.comhttps://facebook.com/

这显然会阻止我的代码遵循301响应。我将我的结果与Fiddler进行了比较;在Fiddler中,它正确地显示了这个标题:

Location: https://www.facebook.com/

我在包括Bing,亚马逊,谷歌和雅虎在内的几个大型网站上进行了测试,我的代码中获得的标题与Fiddler中的标题相同。即使在Facebook响应中,我得到的每个标题都与Fiddler相同,只有一个Location标题。

有什么我做错了吗?这是.NET的SslStream的错误,还是Facebook的错误?

我有以下代码:

TcpClient tcp = new TcpClient(_uri.Host, _uri.Port);

Stream stream;
if (_uri.Scheme == "https") {
    var secureStream = new System.Net.Security.SslStream(tcp.GetStream());
    try {
        secureStream.AuthenticateAsClient(_uri.Host);
        stream = secureStream;
    }
    catch (System.Security.Authentication.AuthenticationException e) {
        secureStream.Close();
        throw e;
    }
} else stream = tcp.GetStream();

我使用以下方式写入流:

var writer = new StreamWriter(stream, Encoding.ASCII);

后来,我有自己的阅读器,它在字节级处理流。这是用于读取HTTP标头的代码段:

public string ReadLine() {
    var s = ReadUntil(0x0D);
    if (_stream.Read(_buffer, 0, 1) != 1) throw new EndOfStreamException();
    if (_buffer[0] != 0x0A) throw new FormatException("Expecting '\\n' after '\\r'");

    return s;
}

public static string ExtractAsciiString(byte[] array, int length) {
    if (length == 0) return string.Empty;

    string s;
    unsafe {
        fixed (byte* p = &array[0]) {
            s = new String((sbyte*)p, 0, length);
        }
    }
    return s;
}

0 个答案:

没有答案