C#Restful client - 连接超时

时间:2016-03-14 15:46:46

标签: c# rest

我正在使用WinForms并访问我的Restful webservice。由于某种原因,一段时间后代码会因连接到服务器时出现超时错误而中断。

问题也可能是由于我的代码设计。 这是我的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 += "&param1=" + doc.param1 + "&param2=" + 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);
}

2 个答案:

答案 0 :(得分:2)

您可以将HttpWebRequest的默认超时更改为大于默认值的某些内容,例如:

request.Timeout = 120000;

我认为默认值为100秒。

您还可以查看此adjusting-httpwebrequest-connection-timeout-in-c-sharp

答案 1 :(得分:0)

表面上看失败,它说远程机器没有响应。最有可能导致

  • 错误的名称或IP地址
  • Windows防火墙在远程计算机上打开