首页 > 解决方案 > C# 无法连接到远程服务器(WebException、SocketException)

问题描述

我尝试将一些数据从网站发布到网络服务,但我得到了这些例外:

System.AggregateException: Une ou plusieurs erreurs se sont produites。---> System.Net.Http.HttpRequestException: 发送请求时出错。---> System.Net.WebException: Unable to connect to remote server ---> System.Net.Sockets.SocketException: 连接尝试失败,因为连接方在一段时间后没有正确响应或建立连接失败,因为连接的主机未能响应 52.211.194.210:443 à System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) à System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) --- Fin de la trace de la pile d' 异常内部 --- à System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) à System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- Fin de la trace de la pile d'exception interne -- - --- Fin de la trace de la pile d'exception interne --- à System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) à ldspoPunchout.ldspoPunchout.PostXMLData(String destinationUrl, String requestXml) --- > (Exception interne #0) System.Net.Http.HttpRequestException: 发送请求时出错。---> System.Net.WebException: Impossible de se connector au serverur distance ---> System.Net.Sockets.SocketException:

我的代码很简单,并且可以在多个站点中使用:

            byte[] data = Encoding.ASCII.GetBytes(requestXml);
            ByteArrayContent byteArray = new ByteArrayContent(data);
            HttpResponseMessage reponse = client.PostAsync(destinationUrl, byteArray).Result;
            Stream stream = reponse.Content.ReadAsStreamAsync().Result;
            StreamReader reader = new StreamReader(stream);
            Test = reader.ReadToEnd();

此代码使用 httpclient 但我也尝试了 webrequest,同样的问题

环境:windows server 2012 R2 标准

我无权访问网络服务的代码,但它是 HTTPS

我很困惑,因为在我的本地机器(Windows 10)上我可以浏览、发布、获取网址,即使在服务器上我也可以用 IE 浏览网址并且它没有代理设置

编辑:忘了提到我可以从服务器上发布到其他网站上!

我认为这是一个超时但添加这些行时:

            client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);

或者

      client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
            client.DefaultRequestHeaders.Add("Keep-Alive", "3600");

没有任何变化,而且无论我设置多少时间并尝试了我阅读的其他各种东西,它都相当快(比如 15 秒):

              ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 
           | SecurityProtocolType.Tls11;
            client.DefaultRequestHeaders.ExpectContinue = false;

如果有人知道这是从哪里来的,那就太好了

提前致谢

编辑:我像这样创建网络请求

                Logger.Log(xml + "                 " + url);
                var webRequest = WebRequest.Create(url);
                PostXMLData(url, xml); 
                return url + "  :  " + Test;

http客户端设置在更高级别:

       public static readonly HttpClient client = new HttpClient();

标签: c#asp.netserverdotnet-httpclient

解决方案


推荐阅读