WebClient.Headers Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
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
Que WebHeaderCollection contiene pares de nombre y valor de encabezado asociados a esta solicitud.
Ejemplos
En el ejemplo de código siguiente se usa la Headers colección para establecer el encabezado application/x-www-form-urlencoded, HTTP Content-Type en para notificar al servidor que los datos del formulario se adjuntan 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 Headers propiedad contiene una WebHeaderCollection instancia de que contiene encabezados de protocolo que envía WebClient 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 WebHeaderCollection objeto. Cualquier intento de establecer uno de estos encabezados restringidos en el WebHeaderCollection objeto asociado a un WebClient objeto producirá una excepción más adelante al intentar enviar la WebClient solicitud.
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 WebClient objeto . 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 HttpWebRequest clase tiene propiedades para establecer algunos de los encabezados anteriores. Si es importante que una aplicación establezca estos encabezados, se debe usar la HttpWebRequest clase en lugar de la WebRequest clase .
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.