WebClient代理无法正常工作

时间:2016-10-29 21:19:14

标签: c# proxy webclient

我创建了这个方法来测试给定的代理数据是否有效:

public static async Task<bool> TestConnection(string ip, int port)
{
    return await Task.Run(() =>
    {
        try
        {
            using (var client = new WebClient())
            {
                client.Headers.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
                var proxy = new WebProxy(ip, port) {UseDefaultCredentials = true};

                client.Proxy = proxy;
                client.OpenRead(new Uri("http://google.com"));
            }

            return true;
        }
        catch (Exception ex)
        {
            Logger.Trace(ex, "Failed to connect to proxy {0}:{1}", ip, port);
        }

        return false;
    });
}

我使用某些网站上列出的不同代理服务器对其进行了多次测试。结果始终是这个例外:

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)

为什么会这样?这些代理不需要身份验证。

0 个答案:

没有答案