现在的位置: 首页 > 综合 > 正文

关于 WebClient类和HttpRequest的方式下载数据的问题

2011年10月18日 ⁄ 综合 ⁄ 共 1496字 ⁄ 字号 评论关闭

1、借用MSDN的简单代码
[C#] 
// Initialize the WebRequest.
WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
// Return the response. 
WebResponse myResponse = myRequest.GetResponse();
// Code to use the WebResponse goes here.
// Close the response to free resources.
myResponse.Close();
2、以上代码在网站可以匿名访问的时候没有任何问题,但是如果使用AD等方式控制了权限,那么就会出现 (401) 未授权的信息。
搞了一上午)
需要定义以下的信息方式,同样借用MSDN的代码

[C#] 
// Create a new webrequest to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create(url);

//注意两种不同的调用方式
//****************************************
//直接调用,使用你当前用户的授权信息
myWebRequest.Credentials=System.Net.CredentialCache.DefaultCredentials;

//使用输入的授权信息
// Set "Preauthenticate"  property to true.  Credentials will be sent with the request.
myWebRequest.PreAuthenticate=true;
Console.WriteLine("\nPlease Enter ur credentials for the requested Url");
Console.WriteLine("UserName");
string UserName=Console.ReadLine();
Console.WriteLine("Password");
string Password=Console.ReadLine();
// Create a New "NetworkCredential" object.
NetworkCredential networkCredential=new NetworkCredential(UserName,Password);
// Associate the "NetworkCredential" object with the "WebRequest" object.
myWebRequest.Credentials=networkCredential;
// Assign the response object of "WebRequest" to a "WebResponse" variable.

//****************************************

WebResponse myWebResponse=myWebRequest.GetResponse();

还有 System.WebClient 等类,会存在相同的信息,大家有兴趣可以看看MSDN,呵呵,可以写一些程序抓取网站的图片、文字等,具体的方式和方法参考MSDN吧,明天虽然要上架了,还是把今天的问题写出来


欢迎光临http://www.shareach.com/

抱歉!评论已关闭.