Authenticating with C# (Sample 2)

Voxeo engineer Zhong Li created some sample code showing how to complete Basic Auth in C#.

/**
 * 
 * author: zli 
 * 
 * This sample code owned by Voxeo Company 
 * Free to use, modify. Without any warranty.
 * 
 */


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Auth
{
    class Program
    {
        static void Main(string[] args)
        {
            String username = "demo";
            String passwd = "12345";
            String url = "http://exammple.com/protected_resource";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Credentials = new NetworkCredential(username, passwd);
            req.AllowAutoRedirect = true;
            req.ContentType = "text/html";
            req.Method = "POST";
            req.Accept = "text/html";
            req.PreAuthenticate = true;

            Stream outStream = req.GetRequestStream();
            String outData = "This is out data";
            byte[] outDataBytes = UnicodeEncoding.ASCII.GetBytes(outData);
            outStream.Write(outDataBytes, 0, outDataBytes.Length);

            outStream.Close();
            WebResponse resp = null;
            try
            {
                resp = req.GetResponse();
            }
            catch (WebException ex)
            {
                resp = ex.Response;

            }
            catch (Exception exother)
            {
                return;
            }

            WebHeaderCollection headers = resp.Headers;
            foreach (string header in headers.Keys)
            {
                Console.WriteLine("{0}:{1}", header, headers[header]);
            }
            Console.WriteLine();
            Stream inStream = resp.GetResponseStream();
            byte[] data = new byte[512];
            int dataLen = -1;
            do
            {
                dataLen = inStream.Read(data, 0, data.Length);
                Console.Write(UnicodeEncoding.ASCII.GetString(data, 0, dataLen));
            } while (dataLen > 0);
            inStream.Close();
            resp.Close();


        }
    }
}