您的位置:首页 > 编程语言 > C#

C# post数据时 出现如下错误: System.Net.WebException: 操作超时

2015-07-01 11:38 691 查看
net(客户端)调用IIS(服务端)出现503后,就报操作超时错误

问题描述:

服务端环境:

IIS

客户端环境:

windowsxp + iis + .net

调用时出现如下错误:

System.Net.WebException: 远程服务器返回错误: (503) 服务器不可用。

在 System.Net.HttpWebRequest.GetResponse()

在 TestWebRequest.WebMessage.SendRequest(Byte[] data, String urlStr)
接着就出现如下错误:

System.Net.WebException: 操作超时

在 System.Net.HttpWebRequest.GetRequestStream()

最后一直是这个错误

System.Net.WebException: 操作超时

在 System.Net.HttpWebRequest.GetRequestStream()

当服务器恢复正常时,访问已经是200时,这个线程还是返回操作超时,经过N多测试,最后如下一行完美解决:

myRequest.ServicePoint.Expect100Continue = false;


修改后的方法为:

public byte[] SendRequest(byte[] data, string urlStr)
{
try
{
Stream streamSend = null;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urlStr);
myRequest.Method = "POST";
myRequest.ContentType = "text/xml";
myRequest.Accept = "*/*";
myRequest.Timeout = 2000;
myRequest.UserAgent = "Mozilla-Firefox-Spider(Wenanry)";
myRequest.ContentLength = data.Length;
//这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
myRequest.ServicePoint.Expect100Continue = false;

HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
myRequest.CachePolicy = noCachePolicy;

try
{
streamSend = myRequest.GetRequestStream();
streamSend.Write(data, 0, data.Length);
streamSend.Close();
}
catch (WebException wex)
{
log.Debug("WebException=" + wex.ToString() + ",wex.Status=" + wex.Status);
if (streamSend != null)
streamSend.Close();
streamSend = null;
myRequest = null;
return null;
}
catch (Exception ex)
{
log.Debug("GetRequestStream=" + ex.ToString());
if (streamSend != null)
streamSend.Close();
myRequest = null;
return null;
}

byte[] byteArr = new byte[256];
Stream streamRequest = null;
try
{
streamRequest = myRequest.GetResponse().GetResponseStream();
}
catch (Exception httpex)
{
log.Debug("SendRequest=" + httpex.ToString());
if (streamRequest != null)
streamRequest.Close();
myRequest = null;
return null;
}
Bytes bytes = new Bytes();
int count = streamRequest.Read(byteArr, 0, 256);
while (count > 0)
{
bytes.writeByteArr(Bytes.byteSub(byteArr, 0, count));
count = streamRequest.Read(byteArr, 0, 256);
}
streamRequest.Close();
return bytes.getByte;
}
catch (Exception eee)
{
log.Debug("eee=" + eee.ToString() + eee.Source + eee.StackTrace);
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: