内联凭据不起作用的HttpWebRequest(即http:// username:password@url.com)

时间:2012-03-17 00:03:36

标签: c# httpwebrequest credentials

我一直在尝试获取HttpWebRequest或其他任何内容,以便为我提供具有所需登录信息的网页的HTML。在普通浏览器中,您可以执行以下操作:

http://username:password@someURL.com

然而,在C#中,这失败了401 Unauthorized。

我也尝试过设置凭据,但也失败了。我试过启用cookie,冒充浏览器,我迷路了......

string credentials = _domain.UserInfo;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_domain);
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

** 另一次尝试 * ***

System.Net.WebRequest req = System.Net.WebRequest.Create(_domain);
if (_domain.UserInfo.Length > 0)
{
    string[] creds = _domain.UserInfo.Split(new char[] { ':' });
    req.Credentials = new System.Net.NetworkCredential(creds[0], creds[1], _domain.Authority);
}

req.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
req.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
System.Net.HttpWebRequest _httpReq = (HttpWebRequest)req;
_httpReq.CookieContainer = new CookieContainer();
_httpReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
_httpReq.UnsafeAuthenticatedConnectionSharing = true;
System.Net.WebResponse resp = req.GetResponse();

我做错了什么?

1 个答案:

答案 0 :(得分:0)

此行为是设计使用(请参阅here。)并且似乎没有一种简单的方法可以更改此行为。相反,您需要将您的凭据放入System.Net.NetworkCredentials对象,并将Credentials属性设置为您的Web请求中的属性。