WebRequest Classe
Definição
Faz uma solicitação para um URI (Uniform Resource Identifier).Makes a request to a Uniform Resource Identifier (URI). Esta é uma classe abstract.This is an abstract class.
public ref class WebRequest abstract
public ref class WebRequest abstract : MarshalByRefObject, System::Runtime::Serialization::ISerializable
public abstract class WebRequest
public abstract class WebRequest : MarshalByRefObject, System.Runtime.Serialization.ISerializable
[System.Serializable]
public abstract class WebRequest : MarshalByRefObject, System.Runtime.Serialization.ISerializable
type WebRequest = class
type WebRequest = class
inherit MarshalByRefObject
interface ISerializable
[<System.Serializable>]
type WebRequest = class
inherit MarshalByRefObject
interface ISerializable
Public MustInherit Class WebRequest
Public MustInherit Class WebRequest
Inherits MarshalByRefObject
Implements ISerializable
- Herança
-
WebRequest
- Herança
- Derivado
- Atributos
- Implementações
Exemplos
O exemplo a seguir mostra como criar uma WebRequest instância e retornar a resposta.The following example shows how to create a WebRequest instance and return the response.
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Text;
int main()
{
// Create a request for the URL.
WebRequest^ request = WebRequest::Create( "http://www.contoso.com/default.html" );
// If required by the server, set the credentials.
request->Credentials = CredentialCache::DefaultCredentials;
// Get the response.
HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());
// Display the status.
Console::WriteLine( response->StatusDescription );
// Get the stream containing content returned by the server.
Stream^ dataStream = response->GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader^ reader = gcnew StreamReader( dataStream );
// Read the content.
String^ responseFromServer = reader->ReadToEnd();
// Display the content.
Console::WriteLine( responseFromServer );
// Cleanup the streams and the response.
reader->Close();
dataStream->Close();
response->Close();
}
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
// Display the status.
Console.WriteLine (response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}
Imports System.IO
Imports System.Net
Imports System.Text
Namespace Examples.System.Net
Public Class WebRequestGetExample
Public Shared Sub Main()
' Create a request for the URL.
Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")
' If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials
' Get the response.
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
' Display the status.
Console.WriteLine(response.StatusDescription)
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
Console.WriteLine(responseFromServer)
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub
End Class
End Namespace
Comentários
Importante
Não recomendamos que você use WebRequest ou suas classes derivadas para um novo desenvolvimento.We don't recommend that you use WebRequest or its derived classes for new development. Em vez disso, use a System.Net.Http.HttpClient classe.Instead, use the System.Net.Http.HttpClient class.
WebRequest é a abstract classe base para. Modelo de solicitação/resposta da rede para acessar dados da Internet.WebRequest is the abstract base class for .NET's request/response model for accessing data from the Internet. Um aplicativo que usa o modelo de solicitação/resposta pode solicitar dados da Internet de maneira independente de protocolo, em que o aplicativo funciona com instâncias da WebRequest classe enquanto as classes descendentes específicas de protocolo executam os detalhes da solicitação.An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request.
As solicitações são enviadas de um aplicativo para um URI específico, como uma página da Web em um servidor.Requests are sent from an application to a particular URI, such as a Web page on a server. O URI determina a classe descendente apropriada a ser criada a partir de uma lista de WebRequest descendentes registrados para o aplicativo.The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest os descendentes normalmente são registrados para lidar com um protocolo específico, como HTTP ou FTP, mas podem ser registrados para lidar com uma solicitação para um servidor ou caminho específico em um servidor.WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.
A WebRequest classe gera um WebException quando ocorrem erros ao acessar um recurso da Internet.The WebRequest class throws a WebException when errors occur while accessing an Internet resource. A Status propriedade é um dos WebExceptionStatus valores que indica a origem do erro.The Status property is one of the WebExceptionStatus values that indicates the source of the error. Quando Status for WebExceptionStatus.ProtocolError , a Response Propriedade conterá o WebResponse recurso de Internet recebido do.When Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource.
Como a WebRequest classe é uma abstract classe, o comportamento real das WebRequest instâncias em tempo de execução é determinado pela classe descendente retornada pelo Create método.Because the WebRequest class is an abstract class, the actual behavior of WebRequest instances at run time is determined by the descendant class returned by Create method. Para obter mais informações sobre valores e exceções padrão, consulte a documentação para as classes descendentes, como HttpWebRequest e FileWebRequest .For more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
Observação
Use o Create método para inicializar novas WebRequest instâncias.Use the Create method to initialize new WebRequest instances. Não use o WebRequest Construtor.Do not use the WebRequest constructor.
Observação
Se o aplicativo que cria o objeto WebRequest for executado com as credenciais de um usuário normal, o aplicativo não poderá acessar os certificados instalados no armazenamento do computador local, a menos que a permissão tenha sido explicitamente concedida ao usuário para fazer isso.If the application that creates the WebRequest object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.
Notas aos Implementadores
Ao herdar do WebRequest , você deve substituir os seguintes membros:,,,,,,,, Method RequestUri ,, Headers ContentLength ContentType Credentials PreAuthenticate GetRequestStream() BeginGetRequestStream(AsyncCallback, Object) EndGetRequestStream(IAsyncResult) GetResponse() , BeginGetResponse(AsyncCallback, Object) e EndGetResponse(IAsyncResult) .When you inherit from WebRequest, you must override the following members: Method, RequestUri, Headers, ContentLength, ContentType, Credentials, PreAuthenticate, GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object), EndGetRequestStream(IAsyncResult), GetResponse(), BeginGetResponse(AsyncCallback, Object), and EndGetResponse(IAsyncResult). Além disso, você deve fornecer uma implementação da IWebRequestCreate interface, que define o Create(Uri) método usado quando você chama Create(Uri) .In addition, you must provide an implementation of the IWebRequestCreate interface, which defines the Create(Uri) method used when you call Create(Uri). Você deve registrar a classe que implementa a IWebRequestCreate interface, usando o RegisterPrefix(String, IWebRequestCreate) método ou o arquivo de configuração.You must register the class that implements the IWebRequestCreate interface, using the RegisterPrefix(String, IWebRequestCreate) method or the configuration file.
Construtores
| WebRequest() |
Inicializa uma nova instância da classe WebRequest.Initializes a new instance of the WebRequest class. |
| WebRequest(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da classe WebRequest das instâncias especificadas das classes SerializationInfo e StreamingContext.Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and StreamingContext classes. |
Propriedades
| AuthenticationLevel |
Obtém ou define valores que indicam o nível de autenticação e representação usada para esta solicitação.Gets or sets values indicating the level of authentication and impersonation used for this request. |
| CachePolicy |
Obtém ou define a política de cache para essa solicitação.Gets or sets the cache policy for this request. |
| ConnectionGroupName |
Quando substituído em uma classe decrescente, obtém ou define o nome do grupo de conexão para a solicitação.When overridden in a descendant class, gets or sets the name of the connection group for the request. |
| ContentLength |
Quando substituído em uma classe descendente, obtém ou define o tamanho de conteúdo dos dados de solicitação enviados.When overridden in a descendant class, gets or sets the content length of the request data being sent. |
| ContentType |
Quando substituído em uma classe descendente, obtém ou define o tipo de conteúdo dos dados de solicitação enviados.When overridden in a descendant class, gets or sets the content type of the request data being sent. |
| CreatorInstance |
Obsoleto.
Quando substituído em uma classe descendente, obtém o objeto de fábrica derivado da classe IWebRequestCreate usada para criar o WebRequest instanciado para criar a solicitação para o URI especificado.When overridden in a descendant class, gets the factory object derived from the IWebRequestCreate class used to create the WebRequest instantiated for making the request to the specified URI. |
| Credentials |
Quando substituído em uma classe descendente, obtém ou define as credenciais de rede usadas para autenticar a solicitação com o recurso da Internet.When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource. |
| DefaultCachePolicy |
Obtém ou define a política de cache padrão para essa solicitação.Gets or sets the default cache policy for this request. |
| DefaultWebProxy |
Obtém ou define o proxy HTTP global.Gets or sets the global HTTP proxy. |
| Headers |
Quando substituído em uma classe descendente, obtém ou define uma coleção de pares nome-valor do cabeçalho associado à solicitação.When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request. |
| ImpersonationLevel |
Obtém ou define o nível de representação para a solicitação atual.Gets or sets the impersonation level for the current request. |
| Method |
Quando substituído em uma classe descendente, obtém ou define o método de protocolo a ser usado nesta solicitação.When overridden in a descendant class, gets or sets the protocol method to use in this request. |
| PreAuthenticate |
Quando substituído em uma classe descendente, indica se é necessário autenticar previamente a solicitação.When overridden in a descendant class, indicates whether to pre-authenticate the request. |
| Proxy |
Quando substituído em uma classe descendente, obtém ou define o proxy de rede a ser usado para acessar esse recurso de Internet.When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource. |
| RequestUri |
Quando substituído em uma classe descendente, obtém o URI do recurso da Internet associado com a solicitação.When overridden in a descendant class, gets the URI of the Internet resource associated with the request. |
| Timeout |
Obtém ou define a duração, em milissegundos, antes que a solicitação atinja o tempo limite.Gets or sets the length of time, in milliseconds, before the request times out. |
| UseDefaultCredentials |
Quando substituído em uma classe descendente, obtém ou define um valor Boolean que controla se DefaultCredentials são enviados com solicitações.When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests. |
Métodos
| Abort() |
Anula a solicitação.Aborts the request. |
| BeginGetRequestStream(AsyncCallback, Object) |
Quando é substituído em uma classe descendente, fornece uma versão assíncrona do método GetRequestStream().When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method. |
| BeginGetResponse(AsyncCallback, Object) |
Quando substituído em uma classe descendente, inicia uma solicitação assíncrona para um recurso de Internet.When overridden in a descendant class, begins an asynchronous request for an Internet resource. |
| Create(String) |
Inicializa uma nova instância de WebRequest com o esquema de URI especificado.Initializes a new WebRequest instance for the specified URI scheme. |
| Create(Uri) |
Inicializa uma nova instância de WebRequest com o esquema de URI especificado.Initializes a new WebRequest instance for the specified URI scheme. |
| CreateDefault(Uri) |
Inicializa uma nova instância de WebRequest com o esquema de URI especificado.Initializes a new WebRequest instance for the specified URI scheme. |
| CreateHttp(String) |
Inicializa uma nova instância HttpWebRequest com a cadeia de caracteres de URI especificada.Initializes a new HttpWebRequest instance for the specified URI string. |
| CreateHttp(Uri) |
Inicializa uma nova instância HttpWebRequest para o URI especificado.Initializes a new HttpWebRequest instance for the specified URI. |
| CreateObjRef(Type) |
Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Herdado de MarshalByRefObject) |
| EndGetRequestStream(IAsyncResult) |
Quando substituído em uma classe descendente, retorna um Stream para gravar dados no recurso da Internet.When overridden in a descendant class, returns a Stream for writing data to the Internet resource. |
| EndGetResponse(IAsyncResult) |
Quando substituído em uma classe descendente, retorna um WebResponse.When overridden in a descendant class, returns a WebResponse. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLifetimeService() |
Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| GetObjectData(SerializationInfo, StreamingContext) |
Popula um SerializationInfo com os dados necessários para serializar o objeto de destino.Populates a SerializationInfo with the data needed to serialize the target object. |
| GetRequestStream() |
Quando substituído em uma classe descendente, retorna um Stream para gravar dados no recurso da Internet.When overridden in a descendant class, returns a Stream for writing data to the Internet resource. |
| GetRequestStreamAsync() |
Quando substituído em uma classe descendente, retorna um Stream para gravar dados no recurso da Internet como uma operação assíncrona.When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation. |
| GetResponse() |
Quando é substituído em uma classe descendente, retorna uma resposta a uma solicitação à Internet.When overridden in a descendant class, returns a response to an Internet request. |
| GetResponseAsync() |
Quando é substituído em uma classe descendente, retorna uma resposta a uma solicitação à Internet como uma operação assíncrona.When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation. |
| GetSystemWebProxy() |
Retorna um proxy configurado com as configurações do Internet Explorer ou do usuário representado no momento.Returns a proxy configured with the Internet Explorer settings of the currently impersonated user. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InitializeLifetimeService() |
Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object. (Herdado de MarshalByRefObject) |
| RegisterPortableWebRequestCreator(IWebRequestCreate) |
Obsoleto.
Registrar um objeto IWebRequestCreate.Register an IWebRequestCreate object. |
| RegisterPrefix(String, IWebRequestCreate) |
Registra um descendente de WebRequest para o URI especificado.Registers a WebRequest descendant for the specified URI. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Quando substituído em uma classe descendente, popula uma instância SerializationInfo com os dados necessários para serializar o WebRequest.When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest. |