【问题标题】:C# Restful client - connection timeoutC# Restful 客户端 - 连接超时
【发布时间】: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 += "&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);
}

【问题讨论】:

  • 我还建议考虑一下为什么您的服务需要这么长时间才能响应。增加超时不是解决方案。问题可能出在我们可能经常监督的其他地方。

标签: c# rest


【解决方案1】:

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

request.Timeout = 120000;

我认为默认是 100 秒。

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

【讨论】:

    【解决方案2】:

    从表面上看失败,它说远程机器没有响应。最可能的原因

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2017-08-20
      • 2013-09-16
      • 2018-12-19
      • 2013-02-09
      相关资源
      最近更新 更多