Posted by: followmcleod | October 19, 2009

HTTP Posting to Twitter Part 1

Twitter APIAs part of my ongoing social media integration research I’ve created my own C# Twitter API in order to understand how the system interacts with external applications. The following is an extract of the fundamental communications hub of the Twitter API.
    
The second and third articles can be found here: HTTP Posting to Twitter Part 2 and HTTP Posting to Twitter Part 3
 
By using the HttpWebRequest class I have created a number of methods that manage http posts and http responses. This is done through the protected virtual method ExecuteString. 
 

protected virtual string ExecuteString(PostingParameters PostingParameters, bool LoginRequired, Method Method)
{
    // Create a new HttpWebRequest object for sending http data to the
    // URL set in the class PostingParameters
    HttpWebRequest Request =
            (HttpWebRequest)HttpWebRequest.Create
                                (PostingParameters.URL);
   

    // Gets or sets a Boolean value that determines whether
    // 100-Continue behaviour is used.
    Request.ServicePoint.Expect100Continue = false;

    // GetMethodType is a method created for setting the
    // Request.Method string according to the Method Enum
    // passed through the parameters. These can be Post,
    // Get, or Delete within this class
    Request.Method = GetMethodType(Method);

    // If Twitter requires a login for a particular post, this will
    // set the security credentials
    if (LoginRequired)
    {
        if (this.Username != String.Empty && this.Password !=             String.Empty)
        {
        Request.Credentials = new NetworkCredential(this.Username,             this.Password);
        }
        else
        {
            throw new ApplicationException(“Login Credentials             Required”);
        }
    }

    PostMessage(ref PostingParameters, ref Request);
    return GetResponse(ref Request);
}

The PostMessage method is used to post the http request to Twitter. If PostingParameters.Message is set to null it is assumed the request is a poll for information rather a post that will change a status or any other piece of information.
    

private void PostMessage(ref PostingParameters PostingParameters, ref HttpWebRequest Request)
{
    byte[] Bytes = null;

    if (PostingParameters.Message != null)
    {
        Request.ContentType = “application/x-www-form-urlencoded”;

        // Convert the message to a byte array
        // before the message is sent to Twitter
        Bytes = System.Text.Encoding.ASCII.GetBytes
                (PostingParameters.Message);

        // Set the ContentLength of the request to the size of         // the byte array
        Request.ContentLength = Bytes.Length;

            // Create a new Stream. The ‘using’ will destroy
            // the object if an exception is thrown.
        using (Stream RequestStream = Request.GetRequestStream())
        {
            RequestStream.Write(Bytes, 0, Bytes.Length);
            RequestStream.Close();
        }
    }
}

The GetResponse method is used to grab the information that is sent back from Twitter. This is normally a string of XML but can also be other server responses.
    
The HttpWebRequest object is passed into the method by reference. The response from Twitter is returned as a string.
    

private string GetResponse(ref HttpWebRequest Request)
{
    string ReturnValue = String.Empty;

    // Get the Response from the Request object
    WebResponse Response = Request.GetResponse();

    // Read the Response into a new Stream. The ‘using’
    // will destroy the object if an exception is thrown
    using (StreamReader Reader =
                new StreamReader(Response.GetResponseStream()))
    {
        // Stream the response into the ReturnValue string
        ReturnValue = Reader.ReadToEnd();
        Reader.Close();
    }

    return ReturnValue;
}

In my next post I’ll expose how I implement a class that communicates directly with Twitter.
    
In the meantime it’ll be good to hear from you. Feel free to post comments and ask questions.
    

About James McLeod, Managing Director at Narvi Digital Media, Brighton

Advertisement

Responses

  1. [...] object and process.    If you missed out on the last article it can be found here: HTTP Posting to Twitter Part 1      The code example below overrides the virtual method ExecuteString within [...]

  2. Interesting code snippets. Would you care for a code review? :-)

    If my team wrote code like that, they’d have quite some feedback…

    • Hey Andy,

      Thanks for the feedback. It’ll be interesting to hear your views, good or bad :)

  3. [...] you haven’t seen my previous posts please feel free to read them here: HTTP Posting to Twitter Part 1 and HTTP Posting to Twitter Part 2. I’m also more than happy to accept comments on all my [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.