有时我在对 WebService 执行 HttpWebRequest 时收到以下错误。我也在下面复制了我的代码。
System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:无法建立连接,因为目标机器主动拒绝它 127.0.0.1:80 在 System.Net.Sockets.Socket.DoConnect(端点 endPointSnapshot,SocketAddress 套接字地址) 在 System.Net.Sockets.Socket.InternalConnect(端点 remoteEP) 在 System.Net.ServicePoint.ConnectSocketInternal(布尔连接失败、套接字 s4、套接字 s6、套接字和套接字、IPAddress 和地址、ConnectSocketState 状态、IAsyncResult asyncResult、Int32 超时、异常和异常) --- 内部异常堆栈跟踪结束 --- 在 System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();