2010-03-18 18 views

Respuesta

17

de http://www.csharp-station.com/HowTo/HttpWebFetch.aspx

HttpWebRequest request = (HttpWebRequest) 
     WebRequest.Create("myurl"); 

     // 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? 

    // print out page source 
    Console.WriteLine(sb.ToString()); 
+7

Hoy en día es _mucho_ más simple: basta con una instancia de un '' WebClient' y llame DownloadString' en él. – Emdot

+0

¿De dónde vienen las variables 'sb' y' buf'? Además, el enlace está muerto ahora. – jbyrd

-1

mirada a System.Net.WebClient, los docs siquiera tiene un ejemplo de recuperar el archivo.

Pero probar si el archivo existe implica pedir el archivo y detectar la excepción si no está allí.

3

una alternativa a HttpWebRequest es WebClient

// create a new instance of WebClient 
    WebClient client = new WebClient(); 

    // set the user agent to IE6 
    client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)"); 
    try 
    { 
     // actually execute the GET request 
     string ret = client.DownloadString("http://www.google.com/"); 

     // ret now contains the contents of the webpage 
     Console.WriteLine("First 256 bytes of response: " + ret.Substring(0,265)); 
    } 
    catch (WebException we) 
    { 
     // WebException.Status holds useful information 
     Console.WriteLine(we.Message + "\n" + we.Status.ToString()); 
    } 
    catch (NotSupportedException ne) 
    { 
     // other errors 
     Console.WriteLine(ne.Message); 
    } 

ejemplo de http://www.daveamenta.com/2008-05/c-webclient-usage/

66

Creo que la clase WebClient es apropiado para que:  

WebClient client = new WebClient(); 
Stream stream = client.OpenRead("http://yoururl/test.txt"); 
StreamReader reader = new StreamReader(stream); 
String content = reader.ReadToEnd(); 

http://msdn.microsoft.com/en-us/library/system.net.webclient.openread.aspx

+0

¿Podría completar los requisitos previos para esto? Me aparece 'El tipo o el nombre del espacio de nombres 'WebClient' no se pudo encontrar' – jbyrd

7

En primer lugar, se puede descargar el archivo binario:

public byte[] GetFileViaHttp(string url) 
{ 
    using (WebClient client = new WebClient()) 
    { 
     return client.DownloadData(url); 
    } 
} 

entonces puede presentar matriz de cadenas para archivo de texto (suponiendo UTF-8 y que es un archivo de texto):

var result = GetFileViaHttp(@"http://example.com/index.html"); 
string str = Encoding.UTF8.GetString(result); 
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); 

Usted Recibirá cada línea de texto (excepto vacía) en cada campo de matriz.

manera
+1

Esto es para la codificación de final de línea de Windows. Si desea dividir líneas para Linux use "\ n". – pbies

0

un poco más fácil:

string fileContent = new WebClient().DownloadString("yourURL");