1

I have a problem when authenticating HttpWebRequest

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

This is my code:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
NetworkCredential networkCredential = new NetworkCredential(username, password);

WebRequest http = HttpWebRequest.Create(new Uri(url));

http.Timeout = timeout;
http.PreAuthenticate = true;
http.Credentials = networkCredential;

try
{
    HttpWebResponse ws = (HttpWebResponse)http.GetResponse();
    Stream str = ws.GetResponseStream();

}
catch (WebException ex)
{
    Console.WriteLine(ex.Message);
}

and I tried to set the authorization in another way:

string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
http.Headers.Add("Authorization", authorization);

but that didn't help either.

Marcus
  • 8,230
  • 11
  • 61
  • 88
T4mer
  • 430
  • 2
  • 7
  • 22

1 Answers1

0

If you are on a corporate network it could be the proxy server presenting the 401 rather than the end web server you are expecting. Keep that in mind.

Try setting authorization from basic to NTLM

Without a large amount of information on the application you are connecting to and the network configuration its just guess work

Nick
  • 1,783
  • 1
  • 15
  • 18