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

本文介绍了解决HTTP请求中401未授权错误的方法,通过设置正确的身份验证信息来成功访问受保护的资源。提供了使用C#进行WebRequest认证的具体代码示例,包括直接使用当前用户的凭据和手动输入用户名及密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值