HttpWebRequest.Proxy Свойство

Определение

Возвращает или задает сведения о прокси-сервере для запроса.

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

Значение свойства

Объект IWebProxy, используемый в качестве прокси-сервера для этого запроса. Значение по умолчанию устанавливается путем вызова свойства Select.

Исключения

Параметру Proxy задается значение null.

Вызывающий объект не имеет разрешения на запрошенную операцию.

Примеры

В следующем примере кода метод используется Proxy для получения сведений о прокси-сервере для запроса.

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

Комментарии

Свойство Proxy определяет объект, используемый WebProxy для обработки запросов к интернет-ресурсам. Чтобы указать, что прокси-сервер не должен использоваться, задайте Proxy для свойства экземпляр прокси-сервера, возвращаемый методом GlobalProxySelection.GetEmptyWebProxy .

Файл конфигурации локального компьютера или приложения может указывать, что используется прокси-сервер по умолчанию. Proxy Если свойство указано, параметры прокси-сервера из Proxy свойства переопределяют файл конфигурации локального компьютера или приложения, и HttpWebRequest экземпляр будет использовать указанные параметры прокси-сервера. Если в файле конфигурации не указан прокси-сервер, а Proxy свойство не указано, класс использует параметры прокси-сервера, HttpWebRequest унаследованные от интернет-Обозреватель на локальном компьютере. Если в Обозреватель Интернета нет параметров прокси-сервера, запрос отправляется непосредственно на сервер.

Класс HttpWebRequest анализирует список обхода прокси-сервера с подстановочными знаками, унаследованными из Интернета Обозреватель так же, как список обхода анализируется непосредственно интернет-Обозреватель. Например, HttpWebRequest класс будет анализировать список обхода "nt*" из Internet Обозреватель как регулярное выражение "nt.*". Таким образом, URL-адрес "http://nt.com" будет обходить прокси-сервер с помощью HttpWebRequest класса и интернет-Обозреватель.

Класс HttpWebRequest поддерживает обход локального прокси-сервера. Класс считает назначение локальным, если выполняется одно из следующих условий:

  • Назначение содержит неструктурированное имя (в URL-адресе нет точек).

  • Назначение содержит адрес замыкания на себя (Loopback или IPv6Loopback) или назначение , назначенное IPAddress локальному компьютеру.

  • Суффикс домена назначения соответствует суффиксу домена локального компьютера (DomainName).

Proxy Изменение свойства после запуска запроса путем вызова GetRequestStreamметода , BeginGetRequestStream, GetResponseили BeginGetResponse вызывает исключение InvalidOperationException. Сведения об элементе прокси-сервера см . в разделе< defaultProxy> Элемент (Параметры сети).

Применяется к

См. также раздел