WebClient.Headers Propriedade

Definição

Obtém ou define uma coleção de pares de nome-valor do cabeçalho associados à solicitação.

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 da propriedade

WebHeaderCollection

Um WebHeaderCollection que contém pares nome-valor do cabeçalho associados a esta solicitação.

Exemplos

O exemplo de código a seguir usa 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 de formulário estão anexados à postagem.

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

Comentários

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

Alguns cabeçalhos comuns são considerados restritos e protegidos pelo sistema e não podem ser definidos ou alterados em um WebHeaderCollection objeto. Qualquer tentativa de definir um desses cabeçalhos restritos no objeto associado a WebHeaderCollection um objeto lançará uma WebClient exceção posteriormente ao tentar enviar a solicitação WebClient .

Os cabeçalhos restritos protegidos pelo sistema incluem, mas não se limitam ao seguinte:

  • Data

  • Host

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

  • Aceitar

  • Conexão

  • Content-Length

  • Esperar (quando o valor for definido como "100-continue"

  • If-Modified-Since

  • Intervalo

  • Transfer-Encoding

A HttpWebRequest classe tem propriedades para definir alguns dos cabeçalhos acima. Se for importante para um aplicativo definir esses cabeçalhos, a HttpWebRequest classe deverá ser usada em vez da WebRequest classe.

Você não deve assumir que os valores de cabeçalho permanecerão inalterados, pois servidores Web e caches podem alterar ou adicionar cabeçalhos a uma solicitação da Web.

Aplica-se a

Confira também