Follow me on Twitter

First time here?

Check out the Archive, and Subscribe to the RSS feed.

C# TwitPic API client

This post was written on March 10, 2009 22:51 by martinhn

I’ve spent some time lately, playing around with the Twitter API. And along with that belongs the TwitPic’s API. I’m using Twitter a lot, to stay in touch with tech news, other developers and just for fun. But it’s getting more and more used for a lot of different things, and I needed it to integrate with an E-commerce platform I’m developing.

The code for post a picture to TwitPic looks like this:

    /// <summary>
    /// URL for the TwitPic API's upload method
    /// </summary>
    private const string TWITPIC_UPLADO_API_URL = "http://twitpic.com/api/upload";

    /// <summary>
    /// URL for the TwitPic API's upload and post method
    /// </summary>
    private const string TWITPIC_UPLOAD_AND_POST_API_URL = "http://twitpic.com/api/uploadAndPost";

    /// <summary>
    /// Uploads the photo and sends a new Tweet
    /// </summary>
    /// <param name="binaryImageData">The binary image data.</param>
    /// <param name="tweetMessage">The tweet message.</param>
    /// <param name="filename">The filename.</param>
    /// <returns>Return true, if the operation was succeded.</returns>
    public bool UploadPhoto(byte[] binaryImageData, string tweetMessage, string filename)
    {
      // Documentation: http://www.twitpic.com/api.do
      string boundary = Guid.NewGuid().ToString();
      string requestUrl = String.IsNullOrEmpty(tweetMessage) ? TWITPIC_UPLADO_API_URL : TWITPIC_UPLOAD_AND_POST_API_URL;
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
      string encoding = "iso-8859-1";

      request.PreAuthenticate = true;
      request.AllowWriteStreamBuffering = true;
      request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
      request.Method = "POST";

      string header = string.Format("--{0}", boundary);
      string footer = string.Format("--{0}--", boundary);

      StringBuilder contents = new StringBuilder();
      contents.AppendLine(header);

      string fileContentType = GetImageContentType(filename);
      string fileHeader = String.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", "media", filename);
      string fileData = Encoding.GetEncoding(encoding).GetString(binaryImageData);

      contents.AppendLine(fileHeader);
      contents.AppendLine(String.Format("Content-Type: {0}", fileContentType));
      contents.AppendLine();
      contents.AppendLine(fileData);

      contents.AppendLine(header);
      contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "username"));
      contents.AppendLine();
      contents.AppendLine(this.Username);

      contents.AppendLine(header);
      contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "password"));
      contents.AppendLine();
      contents.AppendLine(this.Password.ToInsecureString());

      if (!String.IsNullOrEmpty(tweetMessage))
      {
        contents.AppendLine(header);
        contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "message"));
        contents.AppendLine();
        contents.AppendLine(tweetMessage);
      }

      contents.AppendLine(footer);

      byte[] bytes = Encoding.GetEncoding(encoding).GetBytes(contents.ToString());
      request.ContentLength = bytes.Length;

      using (Stream requestStream = request.GetRequestStream())
      {
        requestStream.Write(bytes, 0, bytes.Length);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          using (StreamReader reader = new StreamReader(response.GetResponseStream()))
          {
            string result = reader.ReadToEnd();

            XDocument doc = XDocument.Parse(result);

            XElement rsp = doc.Element("rsp");
            string status = rsp.Attribute(XName.Get("status")) != null ? rsp.Attribute(XName.Get("status")).Value : rsp.Attribute(XName.Get("stat")).Value;

            return status.ToUpperInvariant().Equals("OK");
          }
        }
      }
    }
Tags: , ,
Categories: C#
Actions: E-mail | Permalink | Comments

Comments

March 21. 2009 20:11

DJ

In your code, are you missing a function?

string fileContentType = GetImageContentType(filename);

GetImageContentType, I'm only familiar with this in Java.

DJ

March 21. 2009 20:58

DJ

Sorry, I figured it out, however, I'm not sure how to pass binaryImageData, have an example? Thanks alot.

DJ

March 22. 2009 15:32

MartinHN

You can use the System.IO.File class to do that:

byte[] binaryImageData = File.ReadAllBytes("c:\img.jpg");
UploadPhoto(binaryImageData, "Test", "img.jpg");

MartinHN

March 22. 2009 21:36

DJ

One more problem.
I'm using the following but still getting errors with
XDocument doc = XDocument.Parse(result);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Schema;
using System.IO;
using System.Xml;
//using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

DJ

March 23. 2009 18:23

MartinHN

You need to include System.Xml.Linq as well: using System.Xml.Linq;

MartinHN

June 18. 2009 02:30

trackback

Trackback from Joe Pruitt

Introducing PoshTwitPic

Joe Pruitt

June 26. 2009 01:58

Sanil

Thanks!
I was really stucked at the "posting the image to TwitPic" part, and was really frustated after trying many ways to do that, I even read the whole RFC # 2388 Frown

your post really helped me, and that means I've completed the project Smile
It's now on codeplex http://twipli.codeplex.com

Sanil

July 29. 2009 09:09

balu

HI
thanks for your code.But the
contents.AppendLine();
property is not available in windows mobile projects.I tried
contents.Append("\n");   instead but its not working.
Is there any other way.
Regards
Balu

balu

July 30. 2009 11:21

MartinHN

Hi Balu

According to this: msdn.microsoft.com/.../...ringbuilder_members.aspx

The AppendLine is available in the Compact Framework as well. Which version of the .Net Compact Framework are you using?

MartinHN

November 12. 2009 23:00

pay day loans

Yea nice Work !Laughing

pay day loans

November 18. 2009 08:58

pay day loans

Interesting ... as always - is your blog making any cash advance ? ;)

pay day loans

November 18. 2009 14:20

payday loans

Like your writing! Still you can do some things to improve it.

payday loans

November 22. 2009 10:31

cash loans

Searching for this for some time now - i guess luck is more advanced than search engines Smile

cash loans

November 22. 2009 21:08

cash loans

Searching for this for some time now - i guess luck is more advanced than search engines Smile

cash loans

November 23. 2009 13:04

slots games online

You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

slots games online

November 24. 2009 02:32

Washington Marriage Records

It appears like you have really put a good bit of effort into your article and I require more of these on the Internet these days. I genuinely enjoyed your point of view. I don't really have much to say in reply, I only this minute wanted to comment to reply well done.

Washington Marriage Records

November 25. 2009 23:45

cash today

thanks again

cash today

November 28. 2009 07:45

high jackpots in online casino games

I’ve recently been using C# Generics quite a bit, and loving every single second of it. Recently, I’ve made a personal discovery on the use of Interfaces.

high jackpots in online casino games

December 1. 2009 08:02

payday loans

Yea nice Work !Laughing

payday loans

December 10. 2009 18:26

Clixsense

Is it the problem with all new bloggers to keep reading other blogs or is it just me?

Clixsense

December 10. 2009 18:27

Make extra money online

Is it the problem with all new bloggers to keep reading other blogs or is it just me?

Make extra money online

December 11. 2009 14:38

flash developers

I’ve been away for three weeks and I felt that I was missing your blog greatly.  

flash developers

January 5. 2010 19:05

payday loans

I always wanted to write in my site something like that but I guess you'r faster Smile

payday loans

January 14. 2010 09:02

Medical billing services


very informative thank you for a nice site

Medical billing services

February 2. 2010 07:15

SEO

Hi,

Starting to understand a bit more now... Thanks for keeping it simple!

SEO

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.1.24

About the author

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2009