Posting Image directly in Twitter using Status with Media in C#

I got this task. And after searching a lot, i acheived this.

I was using TweetSharp api in my application.So i tried to achieve with that.
It gives you solution so that you can achieve that by Twitpic Api.

Then I read POST statuses/update_with_media

Tried a lot, not able to do with the C# twitter api’s too like TweetSharp, Hommock etc..
Then Here is the solution 🙂

Step 1: Make Oauth Authorization Header

Simple, Download OAuth.Manager dll from here

Add Reference in your project. And add namespace (Using OAuth;) in your page.

Note : I am assuming here you have made the request to the user before and have configuration key, configuration secret, access token and access secret. You can do it by any C# api.

Step 2: Using this dll and generating header

Setting request Values :

var oauth = new OAuth.Manager();
oauth["consumer_key"] = ~Your application's Key~;
oauth["consumer_secret"] = ~Your application's Secret~;
oauth["token"] = ~Access token~;
oauth["token_secret"] = ~Access secret~;

Making Request :

var url = "https://upload.twitter.com/1/statuses/update_with_media.xml";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
var request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);

Step 3: Adding image to OAuth request and Posting

Here is the message to be uploaded sent as status
string message = "Hello Image Demo";

Here is the image
string imageFile = HttpContext.Current.Server.MapPath("/Images/abc.png"); //Sample image

if (imageFile != null)
{
string boundary = “~~~~~~” +
Guid.NewGuid().ToString().Substring(18).Replace(“-“, “”) +
“~~~~~~”;

var separator = “–” + boundary;
var footer = “\r\n” + separator + “–\r\n”;
string shortFileName = Path.GetFileName(imageFile);
string fileContentType = “image/png”;
string fileHeader = string.Format(“Content-Disposition: file; ” +
“name=\”media\”; filename=\”{0}\””,
shortFileName);
var encoding = System.Text.Encoding.GetEncoding(“iso-8859-1”);

var contents = new System.Text.StringBuilder();
contents.AppendLine(separator);
contents.AppendLine(“Content-Disposition: form-data; name=\”status\””);
contents.AppendLine();
contents.AppendLine(message);
contents.AppendLine(separator);
contents.AppendLine(fileHeader);
contents.AppendLine(string.Format(“Content-Type: {0}”, fileContentType));
contents.AppendLine();

// actually send the request
request.ServicePoint.Expect100Continue = false;
request.ContentType = “multipart/form-data; boundary=” + boundary;

using (var s = request.GetRequestStream())
{
byte[] bytes = encoding.GetBytes(contents.ToString());
s.Write(bytes, 0, bytes.Length);
bytes = File.ReadAllBytes(imageFile);
s.Write(bytes, 0, bytes.Length);
bytes = encoding.GetBytes(footer);
s.Write(bytes, 0, bytes.Length);
}
}

Now Request Made Getting response

using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//Posting Successfull
}
}

All Done. Image Posted Successfully 🙂

Advertisements

20 thoughts on “Posting Image directly in Twitter using Status with Media in C#

  1. gokoulane May 2, 2012 / 5:40 pm

    very useful post . was doing some twitter integration with windows phone app and was searching solution for this prob . luckily found yours . thx abhinav

  2. Gokoulane Ravi May 3, 2012 / 9:51 am

    OAuth.Manager doesnt support wp7 . any alternative pls?

  3. abhinavpratap May 9, 2012 / 8:23 pm

    thnx ravi.. me also searched a lot to get oauth.manager dll :).. don’t know any alternative for wp7.. but in my case it worked well.

  4. suresh August 2, 2012 / 10:46 am

    byte[] bytes = encoding.GetBytes(contents.ToString());
    “encoding” namespace?
    Please reply fast

  5. suresh August 2, 2012 / 12:16 pm

    I am getting 500 internal server error.I used as the same code

    • Joe August 23, 2012 / 10:33 pm

      Hey suresh, I’m getting 500 error too. Did you fix it? Thanks. J

  6. vishal katoch August 16, 2012 / 4:28 pm

    After getting the accesstoken and accesstokensecreate key but still get the 401 unauthorizes exception.

  7. J August 24, 2012 / 12:43 am

    I am getting the 500 internal server error code too. What am I doing wrong? Thanks.

  8. J August 24, 2012 / 1:27 pm

    Here’s what my contents looks like:

    –~~~~~~b5de00faa628c550~~~~~~
    Content-Disposition: form-data; name=”status”

    Hello Image Demo
    –~~~~~~b5de00faa628c550~~~~~~
    Content-Disposition: file; name=”media”; filename=”template.png”
    Content-Type: image/png

  9. J August 24, 2012 / 2:05 pm

    Ok, I think it’s solved. Why…I’m not sure but it works if you use this code:

    http://cropperplugins.codeplex.com/discussions/269906

    Scroll all the way to the bottom and get the code. You don’t have to create the class if you don’t want, you can just make variables. Anyway, it works now, pretty much the same it looks like as the above code but there must be something different.

  10. varshapatil2187 October 19, 2012 / 12:36 pm

    if i post large byte image, then operation timeout error occur,

  11. Rick July 4, 2013 / 6:07 am

    Can anyone tell me if this still works with the new changes to Twitter recently? Thanks

    • John August 7, 2013 / 7:05 pm

      nope

  12. walker August 16, 2013 / 1:22 pm

    Very useful post.
    Thanks

  13. Gaurav Dhol September 25, 2013 / 5:26 am

    It is not working with API 1.1 can you please send code for API 1.1

  14. Fotocum December 31, 2013 / 6:16 pm

    Hello dear ! I am a young ,http://foto-matrix.ru/ – свадебный фотограф, as to render services and reportage
    Portraiture . Spend photographing pets. Shelters for animals ( dogs, cats ) in the presence of free time, ready to hold a free photo shoot
    as well as for children’s homes and similar charitable organizations with them.Offer services advertising photographer for dog kennels (advertising litters of puppies , dogs , etc.)
    For guests of St. Petersburg – photographer ready to spend during your visit to the city on the Neva ! Knowing the city help to schedule a visit interesting places
    ( museums, parks ) .If you wish to use my services , email me in advance that I could prepare the program and coordinate it with you.
    As the picture for me is not just a job , and favorite pastime – I can always conduct a free photography if I liked your idea or event, under TFP.

  15. vignesh August 28, 2014 / 9:42 am

    using (var response = (HttpWebResponse)request.GetResponse())
    {
    if (response.StatusCode == HttpStatusCode.OK)
    {
    //Posting Successfull
    }

    i got error 401.

  16. PontPa November 11, 2014 / 4:10 am

    Find out more! http://asredas.ru
    I used to be very happy to find this web-site.I needed to thanks on your time for this glorious read!! I definitely enjoying each little bit of it and I’ve you bookmarked to check out new stuff you blog post.
    Can I simply say what a relief to search out someone who truly is aware of what theyre speaking about on the internet. You positively know the way to bring an issue to light and make it important. More individuals need to learn this and perceive this aspect of the story. I cant imagine youre no more well-liked since you positively have the gift.
    very good post, i actually love this website, carry on it
    It’s laborious to find knowledgeable individuals on this subject, however you sound like you recognize what you’re talking about! Thanks
    It’s best to take part in a contest for among the best blogs on the web. I’ll recommend this site!
    An interesting dialogue is worth comment. I believe that you must write more on this matter, it won’t be a taboo topic but usually individuals are not enough to talk on such topics. To the next. Cheers
    Whats up! I just wish to give a huge thumbs up for the good information you will have right here on this post. I will likely be coming again to your weblog for more soon.
    This actually answered my downside, thank you!
    There are some fascinating time limits in this article but I don’t know if I see all of them middle to heart. There’s some validity however I will take hold opinion until I look into it further. Good article , thanks and we wish more! Added to FeedBurner as well
    you could have an awesome blog here! would you like to make some invite posts on my weblog?
    Once I originally commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any means you can remove me from that service? Thanks!
    The subsequent time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to read, however I actually thought youd have something fascinating to say. All I hear is a bunch of whining about one thing that you can repair in case you werent too busy looking for attention.
    Spot on with this write-up, I really suppose this web site wants far more consideration. I’ll most likely be once more to learn rather more, thanks for that info.
    Youre so cool! I dont suppose Ive read something like this before. So good to find any person with some original ideas on this subject. realy thanks for beginning this up. this website is something that is needed on the internet, someone with a little originality. helpful job for bringing one thing new to the web!
    I’d should examine with you here. Which isn’t one thing I normally do! I get pleasure from studying a submit that can make people think. Additionally, thanks for allowing me to remark!
    This is the right weblog for anybody who wants to search out out about this topic. You understand so much its nearly exhausting to argue with you (not that I actually would need…HaHa). You positively put a brand new spin on a topic thats been written about for years. Nice stuff, just great!
    Aw, this was a very nice post. In thought I want to put in writing like this moreover – taking time and actual effort to make a very good article… however what can I say… I procrastinate alot and certainly not appear to get one thing done.
    I’m impressed, I must say. Really not often do I encounter a blog that’s both educative and entertaining, and let me tell you, you might have hit the nail on the head. Your thought is excellent; the difficulty is one thing that not enough people are talking intelligently about. I am very joyful that I stumbled across this in my search for one thing relating to this.
    Oh my goodness! an incredible article dude. Thanks However I am experiencing subject with ur rss . Don’t know why Unable to subscribe to it. Is there anybody getting identical rss problem? Anyone who is aware of kindly respond. Thnkx
    WONDERFUL Post.thanks for share..extra wait .. …
    Mobile apps, news and games. Find out more! http://asredas.ru
    There are certainly a variety of particulars like that to take into consideration. That is a nice level to convey up. I provide the ideas above as normal inspiration but clearly there are questions like the one you deliver up the place crucial factor will be working in trustworthy good faith. I don?t know if best practices have emerged around things like that, but I’m positive that your job is clearly identified as a fair game. Each girls and boys feel the impression of just a second’s pleasure, for the rest of their lives.
    A formidable share, I simply given this onto a colleague who was doing a little analysis on this. And he in actual fact bought me breakfast because I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love studying extra on this topic. If possible, as you develop into experience, would you mind updating your blog with extra details? It’s highly useful for me. Huge thumb up for this weblog publish!
    After study a number of of the weblog posts on your web site now, and I truly like your manner of blogging. I bookmarked it to my bookmark web site record and shall be checking back soon. Pls check out my site as properly and let me know what you think.
    Your place is valueble for me. Thanks!…
    This web site is mostly a walk-by means of for the entire information you needed about this and didn’t know who to ask. Glimpse here, and also you’ll undoubtedly discover it.
    There’s noticeably a bundle to find out about this. I assume you made sure nice factors in options also.
    You made some decent points there. I looked on the web for the issue and found most people will go together with along with your website.
    Would you be fascinated about exchanging hyperlinks?
    Nice post. I study one thing more challenging on different blogs everyday. It’ll always be stimulating to read content material from different writers and apply just a little something from their store. I’d desire to use some with the content on my weblog whether you don’t mind. Natually I’ll provide you with a hyperlink on your web blog. Thanks for sharing.
    I discovered your weblog website on google and test a few of your early posts. Proceed to keep up the excellent operate. I just extra up your RSS feed to my MSN News Reader. Searching for ahead to studying extra from you later on!…
    I’m usually to running a blog and i actually admire your content. The article has actually peaks my interest. I’m going to bookmark your site and hold checking for brand spanking new information.

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 )

Google+ photo

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

Connecting to %s