我有一个在 .NETCF 3.5 设备上使用 C# 运行的客户端应用程序,并发送到位于远程的 Java servlet。在对同一个 servlet 进行第三次 HTTP POST 期间,我收到“请求超时”消息。例如,如果 servlet 管理对 Java 服务器的登录,则来自客户端的前两次登录尝试将通过(同一客户端设备),当我尝试第三次时,它将返回“请求超时”异常。服务器。我注意到这种情况总是发生,但我无法找出问题所在。我读到,C# 默认情况下会在 HTTP header 中发送请求 100 继续,因此我使用 ServicePointManager 将请求 100 设置为 false,但无济于事。
这是引发此错误的代码:
serverUrl = url;
string responseFromServer = "";
try
{
System.Net.ServicePointManager.Expect100Continue = false;
int tmp = ServicePointManager.DefaultConnectionLimit;
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(url);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
request.Timeout = (50 * 100);
request.Proxy = System.Net.GlobalProxySelection.GetEmptyWebProxy();
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
catch (Exception WebExp)
{
Logging.Instance.Log(Logging.Levels.Error, "Error in DoPost while retrieving : "+url+ " " + WebExp.Message.ToString());
Logging.Instance.Log(Logging.Levels.Error, WebExp.StackTrace.ToString());
throw WebExp;
}
任何帮助将不胜感激。谢谢!
最佳答案
此行为是由于对 WebResponse 的错误异常处理造成的。您必须始终处理响应并关闭它。否则,第三次尝试 HTTP Webrequest 将会失败,并出现超时(受 WinCE 限制)。
以下源代码是安全的:
HttpWebResponse response = null;
try
{
//...
response = (HttpWebResponse)request.GetResponse();
//...
}
catch(Exception e)
{
// logging, etc.
throw e;
}
finally
{
if(response!=null)
{
response.Close();
}
}
关于c# - 当通过 .NET Compact 从 C# 向同一 Java 服务器发出两个 HttpWebRequest 时,出现 "Request timed out",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472302/