How to Timeout a request using Html Agility Pack

前端 未结 4 668
情书的邮戳
情书的邮戳 2021-01-12 23:56

I\'m making a request to a remote web server that is currently offline (on purpose).

I\'d like to figure out the best way to time out the request. Basically if the

4条回答
  •  醉酒成梦
    2021-01-13 00:54

    Retrieve your url web page through this method:

    private static string retrieveData(string url)
        {
            // used to build entire input
            StringBuilder sb = new StringBuilder();
    
            // used on each read operation
            byte[] buf = new byte[8192];
    
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(url);
            request.Timeout = 10; //10 millisecond
            // execute the request
    
            HttpWebResponse response = (HttpWebResponse)
            request.GetResponse();
    
            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();
    
            string tempString = null;
            int count = 0;
    
            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);
    
                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);
    
                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?
    
            return sb.ToString();
        }
    

    And to use the HTML Agility pack and retrive the html tag like this:

    public static string htmlRetrieveInfo()
        {
            string htmlSource = retrieveData("http://example.com/test.html");
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlSource);
            if (doc.DocumentNode.SelectSingleNode("//body") != null)
            {
              HtmlNode node = doc.DocumentNode.SelectSingleNode("//body");
            }
            return node.InnerHtml;
        }
    

提交回复
热议问题