2015-03-11 10 views
5

Sto provando a leggere l'origine da una pagina che richiede l'autenticazione di base. Tuttavia, utilizzando un'intestazione e anche credenziali nella mia HttpWebRequest, ottengo ancora un'eccezione non autorizzata [401] restituita.Invio dell'autenticazione di base su http

string urlAddress = URL; 
string UserName = "MyUser"; 
string Password = "MyPassword"; 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);  
      if (UserName != string.Empty) 
      { 
       string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(UserName + ":" + Password)); 
       request.Headers.Add("Authorization", "Basic " + encoded); 
       System.Net.CredentialCache credentialCache = new System.Net.CredentialCache(); 
       credentialCache.Add(
        new System.Uri(urlAddress), "Basic", new System.Net.NetworkCredential(UserName, Password) 
       ); 

       request.Credentials = credentialCache; 

      } 

      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //<== Throws Exception 401 

Fiddler Auth Risultati

No Proxy-Authenticate intestazione è presente.
WWW-Authenticate intestazione è presente: Basic realm = "example"

+0

Non so quale versione di .NET si sta utilizzando attualmente, ma ti suggerisco di iniziare a utilizzare 'HttpClient';) –

+0

Confrontare l'intestazione Autorizzazione dalla richiesta all'intestazione Autorizzazione di una richiesta che non restituire 401. – CodeCaster

+0

@CodeCaster: installerò il violinista e pubblicherò i risultati –

risposta

4

Come dice un messaggio:

No Proxy-Authenticate intestazione è presente.

Quindi, la soluzione alternativa:

... 
string urlAddress = "http://www.google.com"; 
string userName = "user01"; 
string password = "puser01"; 
string proxyServer = "127.0.0.1"; 
int proxyPort = 8081; 

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(urlAddress); 

if (userName != string.Empty) 
{ 
    request.Proxy = new WebProxy(proxyServer, proxyPort) 
    { 
     UseDefaultCredentials = false, 
     Credentials = new NetworkCredential(userName, password) 
    }; 

    string basicAuthBase64 = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password))); 
    request.Headers.Add("Proxy-Authorization", string.Format("Basic {0}", basicAuthBase64)); 
} 

using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) 
{ 
    var stream = response.GetResponseStream(); 
    if (stream != null) 
    { 
     //--print the stream content to Console 
     using (var reader = new StreamReader(stream)) 
     { 
      Console.WriteLine(reader.ReadToEnd()); 
     } 
    } 
} 
... 

spero che aiuta.

Problemi correlati