【发布时间】:2016-03-15 00:07:13
【问题描述】:
我正在使用 WinForms 并访问我的 Restful 网络服务。由于某种原因,一段时间后的代码会中断,因为在连接到服务器时会出现超时错误。
问题也可能是由于我的代码设计。 这是我的 Restful 客户端类
public class Restful
{
public string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("MyUserName:MyPassword"));
public string POST(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create("http://myserverdomain.com/api/webservice/someMethod");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.Method = WebRequestMethods.Http.Post;
request.Headers["Authorization"] = this.auth;
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream postStream = null;
try
{
// ERROR IS IN THIS LINE
postStream = request.GetRequestStream();
}
catch (WebException ex)
{
// I'm kind of creating an hack here..which isn't good..
if (ex.Status.ToString() == "ConnectFailure")
{
System.Threading.Thread.Sleep(1000);
this.POST(parameters);
}
}
if (postStream == null)
return string.Empty;
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
return responseValue;
using (var responseStream = response.GetResponseStream())
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
responseValue = reader.ReadToEnd();
return responseValue;
}
}
}
我收到错误消息(在几次成功发送项目后):
无法连接到远程服务器
连接尝试失败,因为连接方在一段时间后没有正确响应,或者连接失败,因为连接的主机没有响应 MyServerIpAddress
有时我向服务器发送数千个项目,有时我只发送 2 或 4 个。所以我在循环中调用此 POST function。
try
{
foreach (app.views.Documents doc in DocumentsView)
{
var parameters = "key=" + doc.key;
parameters += "¶m1=" + doc.param1 + "¶m2=" + doc.param2;
/*
* Validates the response of Restful service.
* The response is always in JSON format.
*/
if (response(Restful.POST(parameters)) == false)
{
MessageBox.Show("Error while sending the ID: " + doc.id.ToString());
break;
};
}
}
catch (Exception ex)
{
MessageBox.Show("Error while sending documents: " + ex.Message);
}
【问题讨论】:
-
我还建议考虑一下为什么您的服务需要这么长时间才能响应。增加超时不是解决方案。问题可能出在我们可能经常监督的其他地方。