Sending Basic authentication over http

偶尔善良 提交于 2019-12-01 05:26:11

As message says:

No Proxy-Authenticate Header is present.

Then, the workaround:

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

I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!