使用HTTPWebRequest获取远程页面的标题

我有一个Web服务,充当网站和一些分析软件之间的接口。 部分分析跟踪需要收获页面标题。 我想使用HTTPWebRequest来调用页面,而不是将其从网页传递到Web服务。

我有代码将获取整个页面并解析html以获取标题标记,但我不想下载整个页面只是为了获取头脑中的信息。

我已经开始了

 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); request.Method = "HEAD"; 

好主意,但HEAD请求只返回文档的HTTP标头。 这不包括title元素,它是HTTP消息体的一部分。

试试这个:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Text.RegularExpressions; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string page = @"http://stackoverflow.com/"; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(page); StreamReader SR = new StreamReader(req.GetResponse().GetResponseStream()); Char[] buf = new Char[256]; int count = SR.Read(buf, 0, 256); while (count > 0) { String outputData = new String(buf, 0, count); Match match = Regex.Match(outputData, @"([^<]+)", RegexOptions.IgnoreCase); if (match.Success) { Console.WriteLine(match.Groups[1].Value); } count = SR.Read(buf, 0, 256); } } } } 

如果您不想要求整个页面,可以分批请求。 http规范定义了一个名为Range的http头。 你会像下面这样使用它:

范围:字节= 0-100

您可以查看返回的内容并找到标题。 如果它不存在,那么请求范围:101-200,依此类推,直到得到你需要的为止。

显然,Web服务器需要支持范围,所以这可能会被击中或错过。

所以我不得不选择……

 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream st = resp.GetResponseStream(); StreamReader sr = new StreamReader(st); string buffer = sr.ReadToEnd(); int startPos, endPos; startPos = buffer.IndexOf("<title>", StringComparison.CurrentCultureIgnoreCase) + 7; endPos = buffer.IndexOf("</title>", StringComparison.CurrentCultureIgnoreCase); string title = buffer.Substring(startPos, endPos - startPos); Console.WriteLine("Response code from {0}: {1}", s, resp.StatusCode); Console.WriteLine("Page title: {0}", title); sr.Close(); st.Close();