C#连接通过代理 [英] C# Connecting Through Proxy
问题描述
我需要通过特定的http代理进行的所有连接一个办公室工作。我需要编写一个简单的应用程序从一个Web服务器查询一些价值观 - 这很容易,如果没有代理。如何让C#应用程序代理感知?我怎样才能使任何类型的连接通过代理?
I work in a office which requires all connections to be made through a specific http proxy. I need to write a simple application to query some values from a webserver - it's easy if there were no proxy. How can I make the C# application proxy-aware? How can I make any sort of connection through a proxy?
推荐答案
这是很容易要么无论是在web.config中或在app.config实现编程,在code或声明。
This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.
您可以通过编程创建像这样的代理:
You can programmatically create a proxy like so:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
你基本上分配 WebProxy
对象的要求
对象的代理
属性。然后,这个要求
将使用代理
定义。
You're basically assigning the WebProxy
object to the request
object's proxy
property. This request
will then use the proxy
you define.
要达到同样的事情声明,你可以做到以下几点:
To achieve the same thing declaratively, you can do the following:
<system.net>
<defaultProxy>
<proxy
proxyaddress="http://[your proxy address and port number]"
bypassonlocal="false"
/>
</defaultProxy>
</system.net>
你的web.config或app.config中之内。该选项可设置所有HTTP请求将使用默认代理。根据需要实现什么,则可能需要或可能不需要一些 defaultProxy <附加属性/ A> / 代理的元素,因此,请参阅这些文档。
within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.
这篇关于C#连接通过代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!