c# - http web request with https and basic authentication

22,400

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();
}
Share:
22,400
user1096865
Author by

user1096865

Updated on January 22, 2020

Comments

  • user1096865
    user1096865 over 4 years

    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();
    
  • John
    John over 8 years
    @Cheese This worked for me, however I had to add webRequest.ContentLength = 0 as it wasn't happy without it even though the body content was 0.
  • Herbert Yu
    Herbert Yu over 8 years
    @John Thanks, added ContentLength. Even my system doesn't need that. I guess some systems need that zero content length.