Unable to read data from the transport connection:An existing connection was forcibly closed by the remote host

放肆的年华 提交于 2019-12-10 18:19:25

问题


I have problem when I try download source page from morizon.pl:

  WebClient webClient = new WebClient();
  try
  {
      string str = webClient.DownloadString("https://www.morizon.pl/");
  }
  catch (Exception ex)
  {
      Console.WriteLine(ex);
  }

I checked similar problem in stackoverflow and edit my code and still nothing, I'm stuck with this problem.

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }

    public CookieAwareWebClient()
        : this(new CookieContainer())
    { }

    public CookieAwareWebClient(CookieContainer c)
    {
        this.CookieContainer = c;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        var castRequest = request as HttpWebRequest;

        if (castRequest != null)
        {
            castRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            castRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36";
            castRequest.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            castRequest.Headers.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
            castRequest.KeepAlive = false;
            castRequest.ProtocolVersion = HttpVersion.Version10;
            castRequest.ServicePoint.ConnectionLimit = 1;
            castRequest.CookieContainer = this.CookieContainer;
        }

        return request;
    }
}

For example google.com I can download with my function but morizon.pl I cannot.


回答1:


As of .NET Framework 4.0 the default security protocol is TLS 1.0 and SSL 3.0.

In your application you may need to enable either TLS 1.1 and/or TLS 1.2.

System.Net.ServicePointManager.SecurityProtocol |= 
    SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

using (WebClient webClient = new WebClient())
{
  string str = webClient.DownloadString("https://www.morizon.pl/");
}

More details in this stackoverflow post.



来源:https://stackoverflow.com/questions/52498248/unable-to-read-data-from-the-transport-connectionan-existing-connection-was-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!