关于 WebClient类和HttpRequest的方式下载数据的问题
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/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步