Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Web-logging, also known as blogging, is a new technology that allows you to publish your ideas to the world quickly. This has been a trend for the last several months. This article will show you how to post blogs to LiveJournal.com programmatically using C#, so that you can implement the functionality in your own application.

You need some familiarization with C# in order to understand the code.

Background

LiveJournal.com is one of the most popular free blog hosts today. That's why I chose this as code sample, because more people can benefit from it. You can always get a free LiveJournal blog account here.

The code provided here allows you to blog programmatically. You can go straight to the code. However, I would also like to show you how it works behind the scene.

You are probably familiar with blogging. If you are not, let me take you through the process of blogging, step-by-step using your mouse and keyboard.

In general, these are the steps you need to do, to blog manually:

The fact is, only 2nd and 3rd are necessary in the code. These are the two major steps, in which you have to send data to the blog host.

So, what's behind the scene?

Here are the steps performed by your browser, and the code I am going to provide does the following using C#:

Using the code

I will show you the most important section of the code. This block of code allows you to send your username and password to the blog server, i.e. the log-in process. After successfully logging-in, you may use similar code to send the blog title and the message body to the blog server. Comments have been added to the code:

public bool Login(string username, string password)
{
   try
   {
      // Prepare the HttpWebRequest to send data to 

      // LiveJournal.com

      string url = 
        string.Format("http://www.livejournal.com/login.bml");
      HttpWebRequest request = 
        (HttpWebRequest) WebRequest.Create(url);
      request.UserAgent = "Mozilla/5.0 (Windows; U; " 
         + "Windows NT 5.1; en-US; rv:1.7) "
         + "Gecko/20040707 Firefox/0.9.2";
      request.Method = "POST";
      request.Accept = 
        "text/xml,application/xml,application/xhtml+xml,"
        + "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
      request.KeepAlive = true;
      request.ContentType = @"application/x-www-form-urlencoded";
      request.Referer = 
       string.Format("http://www.livejournal.com/login.bml?nojs=1");
      request.CookieContainer = cookieContainer;

      // Send the log-in data

      string postData = 
        string.Format("response=&user={0}&"
           + "password={1}&expire=close&"
           + "bindip=no&action%3Alogin=Log+in...", username,"
           + " password); 
      request.Method="POST";
      byte [] postBuffer = 
        System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
      request.ContentLength = postBuffer.Length;
      Stream postDataStream = request.GetRequestStream();
      postDataStream.Write(postBuffer,0,postBuffer.Length);
      postDataStream.Close();

      // Get the response

      HttpWebResponse response =
        (HttpWebResponse) request.GetResponse();
      response.Cookies =
        request.CookieContainer.GetCookies(request.RequestUri);

      // Add the cookie to this instance of object, 

      //so that the cookies can be reused for next request

      Cookies.Add(response.Cookies);

      // Read the response from the stream

      Encoding enc = System.Text.Encoding.UTF8;
      StreamReader responseStream = 
        new StreamReader(response.GetResponseStream(), enc, true);

      string responseHtml = responseStream.ReadToEnd();
      response.Close();
      responseStream.Close();

      // For debug purpose, print out the cookies received from 

      // LiveJournal.com

      foreach (Cookie c in response.Cookies)
      {
         Debug.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
      }

      // Check if log-in is successful

      string successString = 
         "you are now logged in to LiveJournal.com";
      if (responseHtml.IndexOf(successString) >= 0)
      {
         // log-in successfully

         return true;
      } 
      else
      {
         // log-in failed

         return false;
      }
   }
   catch (Exception)
   {
      return false;
   }
}

And here is the code, to call this function in my main application:

static void Main(string[] args)
{
   /* Put your configuration below */
   string username = "YOUR LIVEJOURNAL USERNAME";
   string password = "YOUR LIVEJOURNAL PASSWORD";
   string subject = "This is subject";
   string body = "This is a message body";
   /* End of configuration */

   // Create the LiveJournal object

   LiveJournal lj = new LiveJournal();

   // Log-in using your username and password

   if (lj.Login(username, password))    //  <--- calling the code above

   {
      // if log-in successfully, post the blog

      lj.AddBlog(subject, body);
      System.Console.WriteLine("Blog successfully!");
   } 
   else
   {
      System.Console.WriteLine("Blog failed");
   }
   System.Console.WriteLine("Press any key to close the application...");
   System.Console.ReadLine();
}

The sample source file, you downloaded from the above link, shows the complete code and, how everything works together.

Points of Interest

You probably must have wondered, if the same code works on other blog servers, the answer is yes and no. Yes, it can, but you have to change some code. For example, the data being sent to different blog servers are different. You need to have some network level programming knowledge in order to get these done. There are programs to help you, such as Ethereal or Paros.

Security Notes

There are several points worth mentioning. While you may find the code useful because you can add blogging functionalities to your e-mail clients and instant messenger clients, this (along with some creativity and imagination) can be misused and it can cause security threats:

Questions?

It is difficult for me, to try to explain everything. Please ask me, if there is anything that is not clear. I will try to answer them as clearly as possible.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalnot working with the similar code to connect to asp chat server
niqing
12:36 14 Jul '07  
the chat server uses session cookies, and session_end event to drop the online users..

i have the similar code to connect to the chat server,, but after a while,, the server hits session_end event with my username, i know the app refresh the message.asp every three seconds, so the server shouldn't hit session_end event....
GeneralUgly but working solution
ASPCode.net
3:51 12 Jun '07  
Please read my article

C# code to post to livejournal for an ugly but working solution
Generalthe code doesnt work
lol1878
6:48 17 May '07  
Hi
Could u please update the post code... it doesnt seem to work.

Thanks
GeneralUploading files in similar way?
alex9913
4:22 17 Jul '06  
I know that files could be sent via forms too.
how would it look like - sending an example.txt file like this?

Thanks alot!
Alex, Israel.
GeneralVery useful idea. Have you tried to use it on, say, Yahoo email?
tank209
15:05 7 May '06  

For instance, use a similar tool to send email in yahoo.
Or just read certain info from yahoo where login is required.

I tried your code on a couple of other websites like comcast
and verizon.com. Couldn't get it work.
GeneralRe: Very useful idea. Have you tried to use it on, say, Yahoo email?
Kelvin Tsang
16:56 7 May '06  
You have to capture the network traffic between your computer and the server, and imitate the communication. Sometimes if https is involved, you may need to use different objects for the HTTP requests.

Thanks for being interested in the code.

GeneralIts not working
saishyam
20:36 1 Mar '06  
the code doesn't work

Syam
GeneralRe: Its not working
Kelvin Tsang
5:57 2 Mar '06  
Hi Syam,

No, not anymore, because they have changed their interface and I don't have a chance to update the code. Thanks for pointing this out.
Generalsome observtions
caiafaverde
23:33 21 Feb '05  
The presented code is almost perfect but it works only if LJ user's interface is configured to English. Otherwise (in case of russian, chinese or whatever ) we never find "you are now logged in to LiveJournal.com" string even in case of successfully connection. Instead of this it's possible to search strings common to all languages - in fact, some html tags that are present on received page only in case of successful login. E.g. , that would be "<a href = "/update.bml">" or any other.

Alexei Tocari
GeneralRe: some observtions
Kelvin Tsang
6:03 22 Feb '05  
Hi caiafaverde,

Thanks for your observation, and that's so true. I overlooked the fact that the user interface may be in other languages.

Generalhow to post data other than IIS server such as Apachi
MohdYounisKhan
1:08 17 Feb '05  
I appreciate your point of view, i check it by creating a userName, password and fill the data with the program.

i apply the same technique with the following links, which give me an erroe "405 Method Not Allowed!".

http://www.c-and-e-museum.org/addguest.html[^]

this problem encouter when a web server is used other than IIS

in such case there is no need of cookies, i also change the userAgent, contentType but the problem exist.

if you have some suggestion or idea please forward me.
Frown
GeneralRe: how to post data other than IIS server such as Apachi
Kelvin Tsang
20:39 24 Feb '05  
This method I described is server-independent, so it works with IIS and Apache, and all web servers handling the standard http request / response.

In your case, the problem is probably your request url. When you submit a form, did you set it up to send the request to the form processing script? In this case, it is not necessary addguest.html, but instead, a perl script, or php.

Bear in mind that we are working with no fancy stuffs but only cookies. Smile

Good luck!
GeneralInteresting, it would be better if...
zumanity0
15:50 29 Jan '05  
Thanks for the article, very interesting indeed! It will be better if you can tell more about how to figure out the postData variable. Laugh Regards.
GeneralRe: Interesting, it would be better if...
Kelvin Tsang
16:43 29 Jan '05  
Good you like it. To know how to get the postData variable, you need some knowledge in what network packets are. Network packets, in this context, are the request messages you send to the blog server. You need some tool to capture the request messages.

Understanding the request message is not a trivial task, but I will give it a try. One very good tool is Ethereal, as I suggested in the article. You can following the steps below to capture the request message:
1) Use your favorite browser to browse to your blog server's log-in page
2) type in your username and password, DO NOT press the log-in button yet
3) Run Ethereal, start capturing data
4) Go back to your browser, and click log-in. You should be able to see a lot of messages appearing in Ethereal.
5) In Ethereal, stop capturing data
6) Use the filter to display only HTTP data
7) Look for the request (usually the first one in the message list) that sends your usename and password to the blog server.

In that request, you should be able to see the payload of the packet. Then you may simply copy and paste that payload into the code.

If you google about ethereal, there should be some tutorial showing you how it works. Hope this helps.
GeneralNot a bad read, albeit a little short.
Adam Goossens
0:54 21 Jan '05  
You wrote the article well, and brought up a good idea. The code will break if LiveJournal ever change their publishing mechanism, but that's not important Smile

However, IMO I think it would be good if you added a section on how to submit a new post to LiveJournal (since that is what the title implies the article is about). I know with a little source sniffing anyone could work it out, but you should follow through with the title of your article Big Grin

Good work on the article! I look forward to seeing more from you.

Regards,
-Adam.

This space for rent!
My Blog
GeneralRe: Not a bad read, albeit a little short.
Kelvin Tsang
7:45 21 Jan '05  
Thanks Adam for your support and suggestions. You pointed out the exact weakness of the code. It is only good for its flexibility, because the same mechanism (using HttpWebRequest) can work on all blog hosts assisible via web browsers.

You are right, I will also add the section to submit a new post to LiveJournal.com.


Last Updated 21 Jan 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010