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
.
Запрос запущен с помощью вызова GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object), GetResponse() или BeginGetResponse(AsyncCallback, Object).
Вызывающий объект не имеет разрешения на запрошенную операцию.
Примеры
В следующем примере кода метод используется 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 поддерживает обход локального прокси-сервера. Класс считает назначение локальным, если выполняется любое из следующих условий:
Назначение содержит неструктурированное имя (в URL-адресе нет точек).
Назначение содержит адрес замыкания на себя (Loopback или IPv6Loopback) или назначение , назначенное IPAddress локальному компьютеру.
Суффикс домена назначения соответствует суффиксу домена локального компьютера (DomainName).
Proxy Изменение свойства после запуска запроса путем вызова GetRequestStreamметода , BeginGetRequestStream, GetResponseили BeginGetResponse вызывает InvalidOperationExceptionисключение . Сведения об элементе proxy см . в разделе< defaultProxy> Элемент (Параметры сети).
Применяется к
См. также раздел
Кері байланыс
https://aka.ms/ContentUserFeedback.
Жақында қолжетімді болады: 2024 жыл бойы біз GitHub Issues жүйесін мазмұнға арналған кері байланыс механизмі ретінде біртіндеп қолданыстан шығарамыз және оны жаңа кері байланыс жүйесімен ауыстырамыз. Қосымша ақпаратты мұнда қараңыз:Жіберу және пікірді көру