为 http://user:password@doamin/query Url 创建 HttpWebRequest
我需要将 HttpWebRequest 发送到具有基本内联凭据的 url,如下所示:
http://user:password@doamin/query
我已尝试按原样设置 Url,但它似乎没有传递凭据(得到 403)。
尝试设置 HttpWebRequest 的 Credentials 属性:
request.Credentials = new NetworkCredentials("username","pasword")
并将它们从 url 中删除(生成 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();
I need to send a HttpWebRequest to a url with basic inline credentials as follows:
http://user:password@doamin/query
I've tried setting the Url as is, but it didnt seem to pass the credentials (got 403).
Tried setting the Credentials property of HttpWebRequest:
request.Credentials = new NetworkCredentials("username","pasword")
And removing them from the url (resulting in http://domain/query
) but still got the same result (403).
Using the Url directly from any browser succeeded so the credentials are Ok.
What am I missing?
[UPDATE - ANSWER]
Here's the code that worked for me:
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,创建您的 creds 类:
将其添加到您的 Creds Cache:
现在您可以执行 Web 请求:
然后将 wr.Credentials 设置为 credsCache:
First you create your creds class:
Add it your Creds Cache:
Now you can do a web request:
Then set the wr.Credentials to the credsCache:
纯文本密码不再是 URL 的有效部分(根据相应的 RFC)。正如您已经尝试过的那样,您应该使用
NetworkCredentials
。请参阅 MSDN 获取代码片段/示例:UPD。与 MSDN 代码片段相比,需要在字符串前加上“http://”前缀,以避免出现“Invalid URI”异常。
Plain text password is no longer a valid part of URL (according to respective RFC). You should be using
NetworkCredentials
as you already tried. See MSDN for code snippet/sample:UPD. Compared to MSDN code snippet, one needs to prefix strings with "http://" to avoid "Invalid URI" exception.