Utilizzo delle classi di richiesta e risposta Internet

Per richiedere dati da Internet e leggere la risposta, utilizzare la procedura descritta di seguito

  1. Se si accede a una risorsa quale una pagina Web, creare una classe WebRequest chiamando WebRequest.Create con l'URI della risorsa che si desidera utilizzare, come nell'esempio che segue.

    WebRequest wReq = WebRequest.Create("https://www.contoso.com/");
    [Visual Basic]
    Dim wReq as WebRequest = WebRequest.Create("https://www.contoso.com/")
    

    Nota   In .NET Framework sono disponibili derivazioni di WebRequest e WebResponse specifiche del protocollo per gli URI che iniziano con "http:", "https:" e "file:". Per accedere ad altri protocolli è necessario implementare derivazioni di WebRequest e WebResponse specifiche per ciascun protocollo. Per ulteriori informazioni, vedere Programmazione dei protocolli innestabili.

  2. Impostare i valori delle proprietà necessari nella classe WebRequest. Per supportare l'autenticazione, ad esempio, impostare la proprietà Credentials su un'istanza della classe NetworkCredential, come nell'esempio che segue.

    wReq.Credentials = 
       new NetworkCredential(UserName, SecurelyStoredPassword);
    [Visual Basic]
    wReq.Credentials = _
       New NetworkCredential(UserName, SecurelyStoredPassword)
    

    Nella maggior parte dei casi la classe WebRequest stessa è sufficiente per inviare e ricevere dati. Se è necessario impostare proprietà specifiche del protocollo, tuttavia, eseguire il cast di tipo della classe WebRequest sull'istanza specifica del protocollo. Il cast di tipo sarà valido unicamente se WebRequest è gestito dalla corretta classe derivata da WebRequest. Per accedere ad esempio alle proprietà specifiche HTTP di HttpWebRequest effettuare il cast di tipo di WebRequest su HttpWebRequest. Nell'esempio di codice che segue si illustra come impostare la proprietà specifica per HTTP UserAgent.

    if (wReq is HttpWebRequest) 
    {
       ((HttpWebRequest)wReq).UserAgent = ".NET Framework Example Client";
    }
    [Visual Basic]
    If TypeOf wReq is HttpWebRequest Then
       Ctype(wReq,HttpWebRequest).UserAgent = _
          ".NET Framework Example Client"
    End If
    
  3. Per scaricare una risorsa da Internet chiamare il metodo GetResponse dell'istanza di WebRequest.

    Per caricare dati in una risorsa o inviare a essa dati chiamare il metodo GetRequestStream dell'istanza di WebRequest e utilizzare l'oggetto Stream risultante per scrivere i dati. Al termine del caricamento è necessario chiudere il flusso di richiesta mediante il metodo Stream.Close. Dopo aver chiuso il flusso è possibile chiamare GetResponse per verificare che i dati siano stati ricevuti correttamente dal server. L'effettiva classe dell'istanza di WebResponse restituita è determinata dallo schema dell'URI richiesto. Nell'esempio di codice che segue viene illustrata la creazione di una classe WebResponse mediante il metodo GetResponse.

    WebResponse wResp = wReq.GetResponse();
    [Visual Basic]
    Dim wResp As WebResponse = wReq.GetResponse()
    

    Nota   Dopo aver chiamato WebResponse, è necessario chiudere la risposta con WebResponse.Close o Stream.Close. Se non si chiudono le singole risposte, non vi saranno connessioni al server disponibili e non sarà possibile elaborare ulteriori richieste.

  4. Utilizzare il metodo GetResponseStream della classe WebResponse per ottenere il flusso contenente i dati restituiti dalla risorsa di rete. È inoltre possibile accedere alle proprietà della classe WebResponse o eseguire il cast di tipo di tale classe su un'istanza specifica del protocollo in modo da leggere proprietà specifiche del protocollo stesso. Per accedere ad esempio alle proprietà specifiche di HTTP di HttpWebResponse effettuare il cast di tipo di WebResponse su HttpWebResponse. Nell'esempio di codice che segue si illustra come accedere a una proprietà specifica di HTTP e leggere il flusso di risposta.

    // Read an HTTP-specific property.
    if (wResp is HttpWebResponse) 
    {
       DateTime Updated = ((HttpWebResponse)wResp).LastModified;
    }
    // Get the response stream.
    Stream respStream = wResp.GetResponseStream();
    
    // This example uses a StreamReader to read the entire response
    // into a string and then writes the string to the console.
    StreamReader reader = new StreamReader(respStream, Encoding.ASCII);
    String respHTML = reader.ReadToEnd();
    Console.WriteLine(respHTML);
    
    // Close the response stream.
    respStream.Close();
    [Visual Basic]
    ' Read an HTTP-specific property.
    If TypeOf wResp Is HttpWebResponse Then
      Dim updated As DateTime = Ctype(wResp,HttpWebResponse).LastModified
    End If
    
    ' Get the response stream.
    Dim respStream As Stream = wResp.GetResponseStream()
    
    ' This example uses a StreamReader to read the entire response
    ' into a string and then writes the string to the console.
    Dim reader As StreamReader = _
       New StreamReader(respStream, Encoding.ASCII)
    Dim respHTML as String = reader.ReadToEnd()
    Console.WriteLine(respHTML)
    
    ' Close the response stream
    respStream.Close()
    

    Se nell'applicazione vengono prese in considerazione unicamente le informazioni di intestazione restituite nell'istanza di WebResponse ma non eventuali altri dati restituiti non sarà necessario ottenere il flusso di risposta. Nell'esempio di codice che segue si illustra come restituire al server informazioni di intestazione da un host Internet.

    WebRequest wReq = WebRequest.Create("https://www.contoso.com");
    WebResponse wResp = wReq.GetResponse();
    string server = wResp.Headers["Server"];
    [Visual Basic]
    Dim wReq As WebRequest = WebRequest.Create("https://www.contoso.com")
    Dim wResp As WebResponse = wReq.GetResponse()
    Dim server As String = wResp.Headers("Server")
    
  5. Dopo aver letto i dati della risposta è necessario chiudere eventuali flussi aperti mediante il metodo Stream.Close oppure chiudere la risposta mediante il metodo WebResponse.Close.

    wResp.Close();
    [Visual Basic]
    wResp.Close()
    

    Non è necessario chiamare il metodo Close sia sul flusso di risposta che sulla classe WebResponse, ma comunque tale chiamata non comporta alcun danno. Con WebResponse.Close viene chiamato Stream.Close alla chiusura della risposta.

    Nell'applicazione di esempio che segue è illustrato l'utilizzo delle classi WebRequest e WebResponse.

    using System;
    using System.Net;
    using System.Text;
    using System.IO;
    
    class ClientGet {
       public static void Main(string[] args)
       {
          if (args.Length < 1)
          {
            showusage();
            return;
          }
    
          // Get the URI from the command line.
          Uri site = new Uri(args[0]);
    
          // Create the request instance.
          WebRequest wReq = WebRequest.Create(site);
    
          // Set the HTTP-specific UserAgent property
          if (wReq is HttpWebRequest) 
          {
            ((HttpWebRequest)wReq).UserAgent = 
              ".NET Framework Example Client";
          }
    
          // Get the response instance
          WebResponse wResp = wReq.GetResponse();
    
          // Read an HTTP-specific property.
          if (wResp is HttpWebResponse)
          {
            DateTime updated = ((HttpWebResponse)wResp).LastModified;
          }
    
          // Get the response stream.
          Stream respStream = wResp.GetResponseStream();
    
         // This example uses a StreamReader to read the entire response
         // into a string and then writes the string to the console.
         StreamReader reader = 
           new StreamReader(respStream, Encoding.ASCII);
         String respHTML = reader.ReadToEnd();
         Console.WriteLine(respHTML);
    
         // Close the response and response stream.
         wResp.Close();
       }
       public static void showusage()
       {
          Console.WriteLine("Attempts to GET a URI.");
          Console.WriteLine("\r\nUsage:");
          Console.WriteLine("  ClientGet URI");
          Console.WriteLine("Example:");
          Console.WriteLine("  ClientGet https://www.contoso.com/");
       }
    }
    [Visual Basic]
    Imports System
    Imports System.Net
    Imports System.IO
    Imports System.Text
    Imports Microsoft.VisualBasic
    
    Class ClientGet
    Public Shared Sub Main()
      Dim Args() As String = System.Environment.GetCommandLineArgs()
      If Args.Length < 2 Then
        ShowUsage
        Return
      End If
    
      ' Get the URI from the command line.
      Dim site As Uri = New Uri(Args(1))
    
      ' Create the request instance.
      Dim wReq as WebRequest = WebRequest.Create(site)
    
      ' Set the HTTP-specific UserAgent property.
      If TypeOf wReq Is HttpWebRequest Then
         CType(wReq, HttpWebRequest).UserAgent = _
           ".NET Framework Example Client"
      End If
    
      ' Get the response instance.
      Dim wResp As WebResponse = wReq.GetResponse()
    
      ' Read an HTTP-specific property
      If TypeOf wResp is HttpWebResponse Then
        Dim updated As DateTime = CType(wResp,HttpWebResponse).LastModified
      End If
    
      ' Get the response stream.
      Dim respStream As Stream = wResp.GetResponseStream()
    
      ' Use the Stream. This example reads the entire response with a 
      ' StreamReader into a string, and then writes the string to the 
      ' console.
      Dim reader As StreamReader = _
        New StreamReader(respStream, Encoding.ASCII)
      Dim respHTML As String = reader.ReadToEnd()
      Console.WriteLine(respHTML)
    
      ' Close the response and response stream.
      wResp.Close()
    End Sub
    
    Public Shared Sub ShowUsage
      Console.WriteLine("Attempts to GET a URI")
      Console.WriteLine(Constants.vbCrLf & "Usage")
      Console.WriteLine("  ClientGet URI")
      Console.WriteLine("Example")
      Console.WriteLIne("  ClientGet https://www.contoso.com")
    End Sub
    End Class
    

Vedere anche

Creazione di richieste Internet | Gestione degli errori | Utilizzo di flussi sulla rete | Accesso a Internet tramite proxy | Invio di richieste di dati