GetRequestStream()超时第二次后发生错误

时间:2018-08-08 17:03:20

标签: c# .net http httpwebrequest

我在代码方面遇到一些问题。我正在使用HttpWebRequest类进行操作

代码如下:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768;
ServicePointManager.Expect100Continue = true;
//ServicePointManager.DefaultConnectionLimit = 5;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverName + authorizePath);
request.Abort();
byte[] bearerMatch = UTF8Encoding.UTF8.GetBytes("username:password");

//request.Proxy = null; //<TNI_20180808
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Timeout = 100;
//request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(bearerMatch);

 string content = String.Format(authorizeBody, login, password);
 content = "{" + content + "}";

 try
 {
     using (var writer = new StreamWriter(request.GetRequestStream()))
     {
         writer.Write(content);
     }

     using (WebResponse response = request.GetResponse())
     {
         using (var reader = new StreamReader(response.GetResponseStream()))
         {
             var responseContent = reader.ReadToEnd();
             token = responseContent.Replace('"', ' ').Trim();
         }
         //response.Close();
         //request.Abort();
     }
 }
 catch (Exception ex)
 {

     throw ex;
 }

直到第三次手术,一切都还好,但是不幸的是,我不知道该怎么办。当应用程序尝试第三次创建请求时,出现超时错误:

在System.Net.HttpWebRequest.GetRequestStream(TransportContext&context)

我认为有机会以正确的方式通过关闭请求和响应来解决此问题,但是我不知道该怎么做。增加ServicePointManager.DefaultConnectionLimit操作之后,即可正确完成操作。

能帮我吗?我应该如何以一种好的方式中止或关闭请求/响应?

谢谢!

0 个答案:

没有答案