[已解决问题] c#如何实现通过http代理访问网络
提问时间: 2008-04-29 00:43
悬赏分:50 浏览:124 次

本机通过代理访问网络,用c#编程如何实现

期待高手


最佳答案
遇到问题查MSDN和google,这样解决得更快。

下面的代码来自MSDN Library:
// Create a new request to the mentioned URL.
HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
WebProxy myProxy=new WebProxy();
// Obtain the 'Proxy' of the  Default browser.  
myProxy=(WebProxy)myWebRequest.Proxy;
// Print the Proxy Url to the console.
Console.WriteLine("\nThe actual default Proxy settings are {0}",myProxy.Address);
try
{
Console.WriteLine("\nPlease enter the new Proxy Address that is to be set:");
Console.WriteLine("(Example:http://myproxy.example.com:port)");
string proxyAddress;
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=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();

//---------下面几行是我加的------
StreamReader reader= new StreamReader(myWebResponse.GetResponseStream());
string html = reader.ReadToEnd();

Console.WriteLine(html);
4/29/2008 12:40:51 PM 回答者:deerchao
评论
2周前   DH.伊利丹 :
代码慢慢看,先谢谢deerchao兄的提醒。
我google,百度了一个晚上,实在是没找到有价值的东西,才发帖问的。
网上多是说通过注册表:
修改Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings下的ProxyEnable和ProxyServer实现,但此种方法只适用与局域网用户,拨号用户无效。
鲜有提到WebProxy 这个类,而且不是很具体。于是就发帖问问,看来高手还是很多的。
MSDN我没怎么查过,对他印象不好。可能我技巧不好吧,总找不到我想要的。
得,我再看看MSDN,还望高手再教点技巧。
2周前   deerchao :
像你这个问题,你可以在在MSDN Library的索引页里输入HttpWebRequest,然后找到这个类的文档,看有没有与代理有关的属性,方法。找到相关的属性之后,很可能就找到了示例代码。
1周前   DH.伊利丹 :
myProxy=(WebProxy)myWebRequest.Proxy; 这样编译不通过
1周前   DH.伊利丹 :
我访问到了目标网站,然后如何显示在浏览器中呢?
   您需要登录以后才能回答!
我的问题    我要提问


快到期问题

> 问题排行榜

有不合适内容,建议去除