Compartir a través de


WebClient.Headers Propiedad

Definición

Obtiene o establece una colección de pares de nombre y valor de encabezado asociados a la solicitud.

public:
 property System::Net::WebHeaderCollection ^ Headers { System::Net::WebHeaderCollection ^ get(); void set(System::Net::WebHeaderCollection ^ value); };
public System.Net.WebHeaderCollection Headers { get; set; }
member this.Headers : System.Net.WebHeaderCollection with get, set
Public Property Headers As WebHeaderCollection

Valor de propiedad

Un WebHeaderCollection que contiene pares de nombre y valor de encabezado asociados a esta solicitud.

Ejemplos

En el ejemplo de código siguiente se usa la colección Headers para establecer el encabezado de Content-Type HTTP en application/x-www-form-urlencoded, para notificar al servidor que los datos del formulario están asociados a la publicación.

String^ uriString;
Console::Write( "\nPlease enter the URI to post data to {for example, http://www.contoso.com}: " );
uriString = Console::ReadLine();

// Create a new WebClient instance.
WebClient^ myWebClient = gcnew WebClient;
Console::WriteLine( "\nPlease enter the data to be posted to the URI {0}:", uriString );
String^ postData = Console::ReadLine();
myWebClient->Headers->Add( "Content-Type", "application/x-www-form-urlencoded" );

// Displays the headers in the request
Console::Write( "Resulting Request Headers: ");
Console::WriteLine(myWebClient->Headers);

// Apply ASCII Encoding to obtain the String^ as a Byte array.
array<Byte>^ byteArray = Encoding::ASCII->GetBytes( postData );
Console::WriteLine( "Uploading to {0} ...", uriString );
// Upload the input String* using the HTTP 1.0 POST method.
array<Byte>^responseArray = myWebClient->UploadData( uriString, "POST", byteArray );
// Decode and display the response.
Console::WriteLine( "\nResponse received was {0}",
   Encoding::ASCII->GetString( responseArray ) );
   string uriString;
       Console.Write("\nPlease enter the URI to post data to {for example, http://www.contoso.com} : ");
       uriString = Console.ReadLine();

       // Create a new WebClient instance.
       WebClient myWebClient = new WebClient();
       Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
       string postData = Console.ReadLine();
       myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

 // Display the headers in the request
       Console.Write("Resulting Request Headers: ");
       Console.WriteLine(myWebClient.Headers.ToString());
       
       // Apply ASCII Encoding to obtain the string as a byte array.

       byte[] byteArray = Encoding.ASCII.GetBytes(postData);
       Console.WriteLine("Uploading to {0} ...",  uriString);						
       // Upload the input string using the HTTP 1.0 POST method.
       byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
       
       // Decode and display the response.
       Console.WriteLine("\nResponse received was {0}",
       Encoding.ASCII.GetString(responseArray));
                 
Dim uriString As String
Console.Write(ControlChars.Cr + "Please enter the URI to post data to{for example, http://www.contoso.com} : ")
uriString = Console.ReadLine()

' Create a new WebClient instance.
Dim myWebClient As New WebClient()
Console.WriteLine(ControlChars.Cr + "Please enter the data to be posted to the URI {0}:", uriString)
Dim postData As String = Console.ReadLine()
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded")

' Display the headers in the request
Console.Write("Resulting Request Headers: ")
Console.Writeline(myWebClient.Headers.ToString())

' Apply ASCII Encoding to obtain the string as a byte array.
Dim byteArray As Byte() = Encoding.ASCII.GetBytes(postData)
Console.WriteLine("Uploading to {0} ...", uriString)
' Upload the input string using the HTTP 1.0 POST method.
Dim responseArray As Byte() = myWebClient.UploadData(uriString, "POST", byteArray)
' Decode and display the response.
Console.WriteLine(ControlChars.Cr + "Response received was :{0}", Encoding.ASCII.GetString(responseArray))

Comentarios

Cautela

WebRequest, HttpWebRequest, ServicePointy WebClient están obsoletos y no debe usarlos para el nuevo desarrollo. Use HttpClient en su lugar.

La propiedad Headers contiene una instancia de WebHeaderCollection que contiene encabezados de protocolo que el WebClient envía con la solicitud.

Algunos encabezados comunes se consideran restringidos y están protegidos por el sistema y no se pueden establecer ni cambiar en un objeto WebHeaderCollection. Cualquier intento de establecer uno de estos encabezados restringidos en el objeto WebHeaderCollection asociado a un objeto WebClient producirá una excepción más adelante al intentar enviar la solicitud de WebClient.

Los encabezados restringidos protegidos por el sistema incluyen, pero no se limitan a lo siguiente:

  • Fecha

  • Anfitrión

Además, algunos otros encabezados también están restringidos al usar un objeto WebClient. Estos encabezados restringidos incluyen, pero no se limitan a lo siguiente:

  • Aceptar

  • Conexión

  • Longitud del contenido

  • Espere (cuando el valor se establece en "100-continue"

  • If-Modified-Since

  • Gama

  • Transfer-Encoding

La clase HttpWebRequest tiene propiedades para establecer algunos de los encabezados anteriores. Si es importante que una aplicación establezca estos encabezados, se debe usar la clase HttpWebRequest en lugar de la clase WebRequest.

No debe suponer que los valores de encabezado permanecerán sin cambios, ya que los servidores web y las memorias caché pueden cambiar o agregar encabezados a una solicitud web.

Se aplica a

Consulte también