HttpWebRequest.Proxy Propriedade

Definição

Obtém ou define informações de proxy da solicitação.

public:
 virtual property System::Net::IWebProxy ^ Proxy { System::Net::IWebProxy ^ get(); void set(System::Net::IWebProxy ^ value); };
public override System.Net.IWebProxy? Proxy { get; set; }
public override System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set
Public Overrides Property Proxy As IWebProxy

Valor da propriedade

O objeto IWebProxy a ser usado para o proxy da solicitação. O valor padrão é definido com a chamada à propriedade Select.

Exceções

Proxy é definido como null.

O chamador não tem permissão para a operação solicitada.

Exemplos

O exemplo de código a seguir usa o Proxy método para obter as informações de proxy para a solicitação.

// Create a new request to the mentioned URL.
HttpWebRequest ^ myWebRequest =
    (HttpWebRequest ^) (WebRequest::Create("http://www.microsoft.com"));

// Obtain the 'Proxy' of the  Default browser.  
IWebProxy ^ proxy = myWebRequest->Proxy;
// Print the Proxy Url to the console.
if (proxy) 
{
    Console::WriteLine("Proxy: {0}",
        proxy->GetProxy(myWebRequest->RequestUri));
} 
else 
{
    Console::WriteLine("Proxy is null; no proxy will be used");
}

WebProxy ^ myProxy = gcnew WebProxy;

Console::WriteLine("\nPlease enter the new Proxy Address that is to be set:");
Console::WriteLine("(Example:http://myproxy.example.com:port)");
String ^ proxyAddress;

try 
{
    proxyAddress = Console::ReadLine();
    if (proxyAddress->Length > 0) {
        Console::WriteLine("\nPlease enter the Credentials ");
        Console::WriteLine("Username:");
        String ^ username;
        username = Console::ReadLine();
        Console::WriteLine("\nPassword:");
        String ^ password;
        password = Console::ReadLine();
        // Create a new Uri object.
        Uri ^ newUri = gcnew Uri(proxyAddress);
        // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
        myProxy->Address = newUri;
        // Create a NetworkCredential object and associate it with the Proxy property of request object.
        myProxy->Credentials =
            gcnew NetworkCredential(username, password);
        myWebRequest->Proxy = myProxy;
    }
    Console::WriteLine("\nThe Address of the  new Proxy settings are {0}",
                  myProxy->Address);
    HttpWebResponse ^ myWebResponse =
        (HttpWebResponse ^) (myWebRequest->GetResponse());
// Create a new request to the mentioned URL.				
HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");

// Obtain the 'Proxy' of the  Default browser.
IWebProxy proxy = myWebRequest.Proxy;
// Print the Proxy Url to the console.
if (proxy != null)
{
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
}
else
{
    Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy=new WebProxy();

Console.WriteLine("\nPlease enter the new Proxy Address that is to be set:");
Console.WriteLine("(Example:http://myproxy.example.com:port)");
string proxyAddress;

try
{
    proxyAddress =Console.ReadLine();
    if(proxyAddress.Length>0)
    {
        Console.WriteLine("\nPlease enter the Credentials (may not be needed)");
        Console.WriteLine("Username:");
        string username;
        username =Console.ReadLine();
        Console.WriteLine("\nPassword:");
        string password;
        password =Console.ReadLine();					
        // Create a new Uri object.
        Uri newUri=new Uri(proxyAddress);
        // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
        myProxy.Address=newUri;
        // Create a NetworkCredential object and associate it with the
        // Proxy property of request object.
        myProxy.Credentials=new NetworkCredential(username,password);
        myWebRequest.Proxy=myProxy;
    }
    Console.WriteLine("\nThe Address of the  new Proxy settings are {0}",myProxy.Address);
    HttpWebResponse myWebResponse=(HttpWebResponse)myWebRequest.GetResponse();
' Create a new request to the mentioned URL.				
Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://www.microsoft.com"), HttpWebRequest)

      ' Obtain the 'Proxy' of the  Default browser.  
      Dim proxy as IWebProxy = CType(myWebRequest.Proxy, IWebProxy)
      ' Print the Proxy Url to the console.
If Not proxy Is Nothing Then
    Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri))
Else
    Console.WriteLine("Proxy is null; no proxy will be used")
End If

Dim myProxy As New WebProxy()

Console.WriteLine(ControlChars.Cr + "Please enter the new Proxy Address that is to be set ")
Console.WriteLine("(Example:http://myproxy.example.com:port)")
Dim proxyAddress As String
Try
    proxyAddress = Console.ReadLine()
    If proxyAddress.Length = 0 Then
        myWebRequest.Proxy = myProxy
    Else
        Console.WriteLine(ControlChars.Cr + "Please enter the Credentials (may not be needed)")
        Console.WriteLine("Username:")
        Dim username As String
        username = Console.ReadLine()
        Console.WriteLine(ControlChars.Cr + "Password:")
        Dim password As String
        password = Console.ReadLine()
        ' Create a new Uri object.
        Dim newUri As New Uri(proxyAddress)
        ' Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
        myProxy.Address = newUri
        ' Create a NetworkCredential object and associate it with the Proxy property of request object.
        myProxy.Credentials = New NetworkCredential(username, password)
        myWebRequest.Proxy = myProxy
    End If
    Console.WriteLine(ControlChars.Cr + "The Address of the  new Proxy settings are {0}", myProxy.Address)
    Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)

Comentários

A propriedade Proxy identifica o objeto WebProxy a ser usado para processar solicitações para recursos da Internet. Para especificar que nenhum proxy deve ser usado, defina a propriedade Proxy como a instância de proxy retornada pelo método GlobalProxySelection.GetEmptyWebProxy.

O computador local ou o arquivo de configuração do aplicativo pode especificar que um proxy padrão seja usado. Se a Proxy propriedade for especificada, as configurações de proxy da Proxy propriedade substituirão o computador local ou o arquivo de configuração do aplicativo e a HttpWebRequest instância usará as configurações de proxy especificadas. Se nenhum proxy for especificado em um arquivo de configuração e a Proxy propriedade não for especificada, a HttpWebRequest classe usará as configurações de proxy herdadas da Internet Explorer no computador local. Se não houver configurações de proxy na Internet Explorer, a solicitação será enviada diretamente ao servidor.

A HttpWebRequest classe analisa uma lista de bypass de proxy com caracteres curinga herdados da Internet Explorer o mesmo que a lista de bypass é analisada diretamente por Explorer da Internet. Por exemplo, a HttpWebRequest classe analisará uma lista de bypass de "nt*" da Internet Explorer como uma expressão regular de "nt.*". Portanto, uma URL de "http://nt.com" ignoraria o proxy usando a HttpWebRequest classe e usando Explorer da Internet.

A classe HttpWebRequest dá suporte ao bypass de proxy local. A classe considera um destino como local se qualquer uma das seguintes condições for atendida:

  • O destino contém um nome simples (nenhum ponto na URL).

  • O destino contém um endereço de loopback (Loopback ou IPv6Loopback) ou o destino contém um IPAddress atribuído ao computador local.

  • O sufixo de domínio do destino corresponde ao sufixo de domínio do computador local (DomainName).

Alterar a Proxy propriedade após a solicitação ter sido iniciada chamando o GetRequestStreammétodo , BeginGetRequestStream, GetResponseou BeginGetResponse lança um InvalidOperationException. Para obter informações sobre o elemento proxy, consulte< defaultProxy> Elemento (Configurações de Rede).

Aplica-se a

Confira também