WebClient.Headers Propriedade

Definição

Obtém ou define uma coleção de pares de nomes de cabeçalho/valor associados ao pedido.

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 Propriedade

A contém WebHeaderCollection pares nome/valor do cabeçalho associados a este pedido.

Exemplos

O exemplo de código seguinte utiliza a Headers coleção para definir o cabeçalho HTTP Content-Type para application/x-www-form-urlencoded, notificar o servidor de que os dados do formulário estão anexados à publicação.

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))

Observações

Atenção

WebRequest, HttpWebRequest, ServicePoint, e WebClient são obsoletos, e não deves usá-los para novos desenvolvimentos. Utilize HttpClient em substituição.

A Headers propriedade contém uma WebHeaderCollection instância contendo cabeçalhos de protocolo que envia WebClient com o pedido.

Alguns cabeçalhos comuns são considerados restritos e protegidos pelo sistema, não podendo ser definidos ou alterados num WebHeaderCollection objeto. Qualquer tentativa de definir um destes cabeçalhos restritos no WebHeaderCollection objeto associado a um WebClient objeto lançará uma exceção mais tarde ao tentar enviar o WebClient pedido.

Cabeçalhos restritos protegidos pelo sistema incluem, mas não se limitam aos seguintes:

  • Data

  • Host

Além disso, alguns outros cabeçalhos também são restritos ao usar um WebClient objeto. Estes cabeçalhos restritos incluem, mas não se limitam aos seguintes:

  • Aceitar

  • Connection

  • Tamanho do conteúdo

  • Expect (quando o valor está definido para "100-continue")

  • Se-Modificado-Desde

  • Alcance

  • Transfer-Encoding

A HttpWebRequest classe tem propriedades para definir alguns dos cabeçalhos acima. Se for importante para uma aplicação definir estes cabeçalhos, então a HttpWebRequest classe deve ser usada em vez da WebRequest classe.

Não deve assumir que os valores dos cabeçalhos permanecerão inalterados, pois servidores Web e caches podem alterar ou adicionar cabeçalhos a um pedido Web.

Aplica-se a

Ver também