Skip to main content
 首页 » 编程设计

c#之Web 服务请求在第 3 次命中时超时

2024年01月29日23qlqwjy

我编写了一个 C# 应用程序来将我的数据从 Blinksale 迁移到 Freeagent。这一切都很好,我正在适本地进行各种 Web 服务调用,但是当我作为批处理运行该过程时,它会在导入时到达第 3 个发票并超时。点个赞

            Stream dataStream = request.GetRequestStream (); 

现在我已经联系了非常好的 API 提供者 (Freeagent),他们已经检查了日志,并且进行了前 2 次尝试(每次包含 3 次单独的调用)但是没有迹象表明第三个请求。这将是对此 Web 服务的第 8 个请求,但在此之前可能有相当多的使用类似代码来获取数据。

因此我假设这与我的 .net 代码有关。

我很难分享任何片段,因为发生了太多事情,但基本上我多次做同样的事情。

注意我已经检查过了,这不是第三个请求中的数据(我跳过了它,结果相同)

// Create a request using a URL that can receive a post.  
            WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx "); 
            // Set the Method property of the request to POST. 
            request.Method = "POST"; 
            // Create POST data and convert it to a byte array. 
            string postData = "This is a test that posts this string to a Web server."; 
            byte[] byteArray = Encoding.UTF8.GetBytes (postData); 
            // 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; 
            // 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. 
            WebResponse response = request.GetResponse (); 
            // Display the status. 
            Console.WriteLine (((HttpWebResponse)response).StatusDescription); 
            // 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. 
            string responseFromServer = reader.ReadToEnd (); 
            // Display the content. 
            Console.WriteLine (responseFromServer); 
            // Clean up the streams. 
            reader.Close (); 
            dataStream.Close (); 
            response.Close (); 

请您参考如下方法:

您将显式关闭所有内容 - 这意味着如果抛出任何异常,您将不会关闭任何内容。对 WebResponse 和所有涉及的流使用 using 语句。通常“网络请求在第三次尝试时超时”问题是是由于连接没有正确关闭......虽然看起来你正在关闭所有东西,但在成功的情况下,可能会有一些微妙之处涉及。 using 语句更加健壮。

例如:

string responseText; 
using (WebResponse response = request.GetResponse()) 
{ 
    Console.WriteLine (((HttpWebResponse)response).StatusDescription); 
    using (Stream responseStream = response.GetResponseStream()) 
    using (StreamReader reader = new StreamReader(responseStream)) 
    { 
        responseText = reader.ReadToEnd(responseText); 
    } 
} 
Console.WriteLine(responseText);