用于建立持久连接的HTTP webrequest

时间:2018-01-05 07:39:17

标签: c#

如何在同一连接中发出第二个请求?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("String.url");
WebResponse response = request.GetResponse();

Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();

stream.Dispose();
reader.Dispose();

2 个答案:

答案 0 :(得分:1)

HTTP Web请求建立持久连接.....你可以同时使用" GET"或" POST" 你可以增加你想要多少的连接(例如3到20或50 ......等)

           string webpageContent = "";
           byte[] byteArray = Encoding.UTF8.GetBytes("value");
           HttpWebRequest webRequest (HttpWebRequest)WebRequest.Create(URL);
           webRequest.Method = "POST";
           webRequest.KeepAlive = true;
           webRequest.Timeout = 120000;
           System.Net.ServicePointManager.DefaultConnectionLimit = 3;
           webRequest.ContentType = "application/x-www-form-urlencoded";
           webRequest.ContentLength = byteArray.Length;
           using (Stream webpageStream = webRequest.GetRequestStream())
           {
               webpageStream.Write(byteArray, 0, byteArray.Length);
           }
           using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
           {
               using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
               {
                   webpageContent = reader.ReadToEnd();
               }
           }

答案 1 :(得分:0)

KeepAlive上的HttpWebRequest属性用于保持连接。它默认为true

此处提供了更详细的文档:

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive(v=vs.110).aspx