Как получить заголовок веб-страницы с помощью веб-клиента? - PullRequest
0 голосов
/ 22 апреля 2020

У меня проблема с подключением к веб-клиенту. На большинстве сайтов нет проблем с получением заголовка страницы, но при тестировании он обнаружил один сайт с ошибкой «Базовое соединение было закрыто: произошла непредвиденная ошибка на конкретном сайте получения. » это: "https://www.modbee.com/opinion/letters-to-the-editor/article111712867.html".

private string GetTitle(string link)
    {
        try
        {
            string html = webClient.DownloadString(link);
            Regex reg = new Regex("<title>(.*)</title>");
            MatchCollection m = reg.Matches(html);
            if (m.Count > 0)
            {
                return m[0].Value.Replace("<title>", "").Replace("</title>", "");
            }
            else
                return "";
        }
        catch (Exception e)
        {
            return labelError.Text = "You should insert correct URL\n";
        }

    }

1 Ответ

1 голос
/ 22 апреля 2020

Если вы хотите загрузить html и проверить регулярные выражения, вы можете использовать приведенный ниже фрагмент кода.

    /*usage:*/
//HttpGet(new Uri("https://www.modbee.com/opinion/letters-to-the-editor/article111712867.html"));

public static string HttpGet(Uri uri) {
 HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
 request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

 using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
 using(Stream stream = response.GetResponseStream())
 using(StreamReader reader = new StreamReader(stream)) {
  var str = reader.ReadToEnd();
  Regex reg = new Regex("<title>(.*)</title>");
  MatchCollection m = reg.Matches(str);
  if (m.Count > 0) {
   return m[0].Value.Replace("<title>", "").Replace("</title>", "");
  } else
   return "";
 }
}
...