
你已经在以前的文章中讨论如何对 将获得的内容 通过编程语言的 Web 页 PHP. 这次你要展示如何你可以做同样 C#. A continuación tienes el código y posteriormente pasamos a explicártelo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public static string getContenidoWeb(string url){ //Verifico que tenga prefijado el tipo de protocolo if (!url.Contains ("http://") || !url.Contains ("https://")) { url = "http://" + url; } //Envío petición y recibo la respuesta Uri uri = new Uri (url); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create (uri); System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse (); //Proceso respuesta y convierto el flujo de llegada en cadena de caracteres System.IO.StreamReader input = new System.IO.StreamReader (res.GetResponseStream ()); char[] chrBuff = new char[256]; int intLen = 0; string strSource = ""; do{ intLen = input.Read(chrBuff, 0, 256); string strBuff = new string(chrBuff, 0, intLen); strSource += strBuff; }while (intLen > 0); return strSource; } |
原则, 我们创建这个函数作为 静态 叫它而无需创建它们属于类的一个实例, 虽然它是 你的决定 放置在此函数 适当的类 并将它设置为静态或不. 此外留在你的手 处理和错误处理 什么, 为简单起见, 我们有排除它.
正如你可以看到, 此函数将作为 参数 的 URL 要从中获取您的代码的 web 站点, 在文本字符串的形式. 一旦它被称为, 第一件事是 检查 que la url que le llega como parámetro tenga prefijado el protocolo HTTP o HTTPS y, 如果不是这样, 添加它是.
然后, 创建一份请愿书 区域性 y obtiene la respuesta en el objeto de la clase HttpWebResponse. 最后, 将转换 的 流量 在一个数据到达 链 字符, 返回 这是 结果 对此函数的调用.

我们的留言或输入到论坛