使用WebClient时遇到“A connection atte

2018-12-05  本文已影响17人  重睛鸟

状况

构建一个Azure Function用于定时下载数据到Azure Storage Account里的Blob下。下载数据的部分用WebClient来处理。但是每次触发都报了连接超时的错误。

错误:

A connection attempt failed because the connected party did not properly respond after a period of time

代码:

            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                string sourceUrl = "https://i0.kym-cdn.com/photos/images/original/001/287/555/106.jpg";
                try
                {
                    using (Stream stream = client.OpenRead(new Uri(sourceUrl)))
                    {
                        await SaveToBlobAsync(stream, log);
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                    throw;
                }
            }

原因

应该是公司内部网络的防火墙限制导致的,但是没法改变。

解决方法

为了能够顺利调试程序,为WebClient加上Proxy后成功下载数据。

            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                WebProxy proxy = new WebProxy("your proxy host IP", port);
                client.Proxy = proxy;
                string sourceUrl = "https://i0.kym-cdn.com/photos/images/original/001/287/555/106.jpg";
                try
                {
                    using (Stream stream = client.OpenRead(new Uri(noaaSourceUrl)))
                    {
                        await SaveToBlobAsync(stream, log);
                    }
                }
                catch (Exception ex)
                {
                    log.LogError(ex.Message);
                    throw;
                }
            }

参考资料

https://stackoverflow.com/questions/17693353/a-connection-attempt-failed-because-the-connected-party-did-not-properly-respon
上一篇 下一篇

猜你喜欢

热点阅读