c# - http web request with https and basic authentication

user1096865 picture user1096865 · May 14, 2013 · Viewed 21.5k times · Source

I'm trying to do a webrequest over a https url with basic authentication. And its not working! below is my code, it actually works if i use a non secure url vs the secure one, and i can't figure out what i'm doing wrong. Works just find with non secure, but when a secure url is used, i get a 401 user auth error. Could it be someone set up wrong on the server, or is it my code?

Could someone help me?

        var req = System.Net.HttpWebRequest.Create(Url) as HttpWebRequest;
        req.Method = Method.ToString();
        req.ContentType = "application/json";
        req.Date = RequestTime;
        req.Proxy = null;
        string credentials = String.Format("{0}:{1}", "xxxx", "xxxx");
        byte[] bytes = Encoding.ASCII.GetBytes(credentials);
        string base64 = Convert.ToBase64String(bytes);
        string authorization = String.Concat("Basic ", base64);
        req.Headers.Add("Authorization", authorization);
        HttpWebResponse response = (HttpWebResponse)req.GetResponse();
    Stream receiveStream = response.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
        string responsebody = readStream.ReadToEnd();
        Console.WriteLine(responsebody);

        response.Close();
        readStream.Close();

Answer

Herbert Yu picture Herbert Yu · Apr 3, 2014

This works for me:

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.ContentLength = 0; // added per comment
string autorization = "username" + ":" + "Password";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("AUTHORIZATION", autorization);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK) Console.WriteLine("{0}",webResponse.Headers);
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
    string s = reader.ReadToEnd();
    Console.WriteLine(s);
    reader.Close();
}