HttpClient Received an unexpected EOF or 0 bytes from the transport stream

請求https連接時報錯,奇怪的是pc1正常,pc2異常html

Unhandled Exception: System.AggregateException: One or more errors occurred. ( Received an unexpected EOF or 0 bytes from the transport stream.) ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
at System.Net.Security.SslStreamInternal.<FillBufferAsync>g__InternalFillBufferAsync|38_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)async

 

緣由:大概是請求時默認了一個過期了的ssl協議ide

解決:指定tls 1.0或其餘有效協議,參考https://stackoverflow.com/questions/25414907/authenticateasclient-system-io-ioexception-received-an-unexpected-eof-or-0-byturl

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var html = GetClientStringAsync("https://**********").Result;
        Console.Write(html);
        Console.ReadLine();
    }

    public static async Task<string> GetClientStringAsync(string url, string encoding = "utf-8")
    {
        var result = string.Empty;
        var httpClientHandler = new HttpClientHandler
        {
            SslProtocols = System.Security.Authentication.SslProtocols.Tls };
        HttpClient client = new HttpClient(httpClientHandler);
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        var bytes = await client.GetByteArrayAsync(url);
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        result = Encoding.GetEncoding(encoding).GetString(bytes);
        return result;
    }
}
相關文章
相關標籤/搜索