C# Restful客户端-连接超时

Lin*_*ode 2 c# rest

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

该问题也可能是由于我的代码设计造成的。这是我的 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误(在成功发送一些项目后):

无法连接到远程服务器

连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应 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);
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ouk 5

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

request.Timeout = 120000;
Run Code Online (Sandbox Code Playgroud)

我认为默认是 100 秒。

您还可以检查此adjustment-httpwebrequest-connection-timeout-in-c-sharp