Twitter for me is something that I get really little value out of. Sure there are some decent links thrown out on there but I usually see the same things on the various blogs that I follow. Not to mention, I don't care what anyone else is doing at any given time. At the same time I've been told multiple times by my friends in marketing that it's a great tool that I can use to do, well, something. I usually stop listening before they finish the sentence. But I am a fan of new tools so I figured I might as well learn how to use it.
There are a ton of already made wrappers for the Twitter API and in fact I use one here on the site (although modified slightly). However I was curious how it all worked and decided to write some code which I figured I might as well share with you:
public static class Twitter
{
public static string Post(string Status, string UserName, string Password)
{
string URL = "http://twitter.com/statuses/update.xml";
string Data = "status=" + HttpUtility.UrlEncode(Status);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
if (!(string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)))
{
Request.Credentials = new NetworkCredential(UserName, Password);
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
Request.ServicePoint.Expect100Continue = false;
byte[] Bytes = Encoding.UTF8.GetBytes(Data);
Request.ContentLength = Bytes.Length;
using (Stream RequestStream = Request.GetRequestStream())
{
RequestStream.Write(Bytes, 0, Bytes.Length);
using (WebResponse Response = Request.GetResponse())
{
using (StreamReader Reader = new StreamReader(Response.GetResponseStream()))
{
return Reader.ReadToEnd();
}
}
}
}
return "";
}
}
The code above does a simple status update. It turns out that Twitter uses a simple REST API. As such you'll notice that the code sets up an url with the status information, sets up a web request, and sends it off (returning the response to the user which is an xml document). It's pretty simple really but there is one item that threw me off. You'll notice that there is a line that has Expect100Continue=false. It turns out that Twitter does not like the 100-Continue header. In fact if you send that header it will instantly throw out whatever you send it. I have no idea why. I'm certain that there is a reason, I just don't know what it is. Anyway, by setting that to false you can get around that issue. Other than that, it's pretty simple. So try it out, leave feedback, and happy coding.
f8b67080-e2cb-4452-a7ec-0116d85fa658|0|.0