远程服务器返回一个错误:(401)未授权

本文关键字:错误 授权 一个 服务器 返回 | 更新日期: 2023-09-27 18:15:11

我写了下面的代码:

string _response = null;
string _auth = "Basic";
Uri _uri = new Uri("http://my.domain.local/my-page.aspx");
HttpWebRequest _req = (System.Net.HttpWebRequest)WebRequest.Create("http://api.olr.com/Service.svc");
CredentialCache _cc = new CredentialCache();
HttpWebResponse _res = default(HttpWebResponse);
StreamReader _sr = default(StreamReader);
_cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc"));
_req.PreAuthenticate = true;
_req.Credentials = _cc.GetCredential(_uri, _auth);
var response = _req.GetResponse();
System.IO.StreamReader sr =
                new System.IO.StreamReader(_res.GetResponseStream());
//_sr = new StreamReader(_res.GetResponseStream);
_response = _sr.ReadToEnd();
_sr.Close();

但得到:

远程服务器返回错误:(401)Unauthorized.

var response = _req.GetResponse();

远程服务器返回一个错误:(401)未授权

您在"http://api.olr.com/Service.svc"中漏掉了"h "

 _cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc"));
并设置WebProxy
System.Net.WebProxy proxy = new WebProxy("http://api.olr.com", true);
proxy.Credentials = new NetworkCredential("platinum", "01CFE4BF-11BA", "http://api.olr.com/Service.svc");
_req.Proxy = proxy;

我认为您的NetworkCredential构造不正确。根据MSDN文档,第三个属性是域名,但是您传递的是完整的URL。您需要从第三方那里找到正确的域名。

同时,您可以尝试将该属性保留,看看登录是否成功。