Posts tagged ‘authenticate’

C# http authenticate

Sometimes URL requests are authenticated by the server your running against. For example if you want to update your Twitter status. Let’s take a look how we can do that easy.

using System.Net;
try
{
    string sURL = “http://twitter.com/statuses/update.xml?status=” + sText;
    // Create the web request
    HttpWebRequest request = WebRequest.Create(sURL) as HttpWebRequest;

    // Add authentication to request
    request.Credentials = new NetworkCredential(“myaccount”, “mypassword”);
    request.PreAuthenticate = true;
    request.Method = “POST”;

    // Get response
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            // Console application output
            StringBuilder body = new StringBuilder(reader.ReadToEnd());
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}