C# – The remote server returned an error: (401) Unauthorized

asp.netcnet

I have written this code:

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();

but getting:

The remote server returned an error: (401) Unauthorized.

at

var response = _req.GetResponse();

Best Answer

you missed 'h' in "http://api.olr.com/Service.svc"

 _cc.Add(_uri, _auth, new NetworkCredential("username", "password", "ttp://api.olr.com/Service.svc"));

and also set 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;
Related Topic