我需要将HttpWebRequest发送到具有基本内联凭据的URL,如下所示:
http://user:password@doamin/query
我已经尝试按原样设置Url,但它似乎没有通过凭据(得到403) 尝试设置HttpWebRequest的Credentials属性:
request.Credentials = new NetworkCredentials("username","pasword")
从网址中删除它们(产生http://domain/query
)但仍然得到相同的结果(403)。
直接从任何浏览器使用Url成功,因此凭据正常。
我错过了什么?
[更新 - 答案]
这是适用于我的代码:
string credentials = "username:password";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(formattedUrl);
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
答案 0 :(得分:1)
首先创建你的信用等级:
NetworkCredential myCred = new NetworkCredential("username", "password");
添加你的Creds Cache:
CredentialCache credsCache = new CredentialCache();
credsCache.Add(new Uri("www.foo.com"), "Basic", myCred);
WebRequest wr = WebRequest.Create("www.foo.com");
wr.Credentials = credsCache;
然后将wr.Credentials设置为credsCache
答案 1 :(得分:0)
纯文本密码不再是URL的有效部分(根据相应的RFC)。你应该尝试使用NetworkCredentials
。见MSDN for code snippet/sample:
NetworkCredential myCred = new NetworkCredential(
SecurelyStoredUserName,SecurelyStoredPassword,SecurelyStoredDomain);
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri("http://www.contoso.com"), "Basic", myCred);
myCache.Add(new Uri("http://app.contoso.com"), "Basic", myCred);
WebRequest wr = WebRequest.Create("http://www.contoso.com");
wr.Credentials = myCache;
UPD。与MSDN代码段相比,需要在字符串前加上“http://”以避免“无效的URI”异常。