Ways to Speed ​​Up WebRequests?

I made an application that can access and manage Onvif cameras, which makes it good enough. However, this is the first time I am building any application that uses such web requests (or in general), so I assume that I'm probably using fairly simple methods. Part of the code, I wonder, is:

Uri uri = new Uri( String.Format("http://" + ipAddr + "/onvif/" + "{0}", Service)); WebRequest request = WebRequest.Create((uri)); request.Method = "POST"; byte[] b = Encoding.ASCII.GetBytes(PostData); request.ContentLength = b.Length; //request.Timeout = 1000; Stream stream = request.GetRequestStream(); //Send Message XmlDocument recData = new XmlDocument(); try { using (stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); } //Store response var response = (HttpWebResponse) request.GetResponse(); if (response.GetResponseStream() != null) { string responsestring = new StreamReader(response.GetResponseStream()) .ReadToEnd(); recData.LoadXml(responsestring); } } catch (SystemException e) { MessageBox.Show(e.Message); } return recData; } 

The code works fine, however, using written assertions, I found that the first request takes about 400 ms, and the subsequent ones from 10 to 20 ms. Can I do something to speed up the first request?

+5
source share
2 answers

You do it just fine. The reason for the time difference to complete may be caused by HTTP Keep-Alive . By default, the same connection is reused for subsequent requests. Therefore, the first request should establish a connection, which probably requires more time. The rest of the requests use the same already open connection.

+5
source

In addition to potential problems with the network and server, the request itself matters. You can reduce the size of the request or break it and upload files asynchronously.

Out of the box web servers do not take 400 ms to complete a simple request.

0
source

Source: https://habr.com/ru/post/1241717/


All Articles