Friday, December 11, 2009

xml rpc tricks

While Xmlrpc in theory is a really nice feature, in practice it's really hard to work with. Never considered myself as a XML type of guy and now we're adding a whole new level of rpc urls, authentication etc.

I bet there might be some nice library out there, but when I need to get somethiung done I always take the easy way out - so here I poresent my quick and dirty code for posting a blog entry to your livejournal blog from C#:

I started out with how I wanted the C# code to look:



protected void LiveJournalPost(string sHeader, string sTxt, string Username, string Password, string RpcUrl)
{
}




And here's that code:



...
string sTxtPostData = @"

LJ.XMLRPC.postevent




username
" + Username + @"

password

" + Password + @"

event
" + sTxt + @"



subject
" + sHeader + @"

lineendings

pc

year
" + DateTime.Now.Year.ToString() + @"


mon
" + DateTime.Now.Month.ToString() + @"

day

" + DateTime.Now.Day.ToString() + @"

hour
" + DateTime.Now.Hour.ToString() + @"


min
" + DateTime.Now.Minute.ToString() + @"






";

WebHelper.PostXml(RpcUrl, sTxtPostData);


...






Building up the XML the RPC endpoint at Livejournal wants to see by just creating a long string.

And here's the WebHelper.PostXml code:




public static string PostXml(string url, string sPostData)
{
string sRet = "ERROR";
System.Net.WebClient oCli = null;
try
{
oCli = new WebClient();
oCli.Headers.Add("Content-Type", "text/xml");
byte[] byteArray = Encoding.ASCII.GetBytes(sPostData);
byte[] responseArray = oCli.UploadData(url, "POST", byteArray);
sRet = Encoding.ASCII.GetString(responseArray);

}
catch (WebException ex)
{
//Console.Write(ex.Message);
}
if (oCli != null)
{
oCli.Dispose();
oCli = null;
}
return sRet;

}


So, calling it is like:

LiveJournalPost("The post header", "And some post content bla bla", "ljusername", "ljpassword", "http://www.livejournal.com/interface/xmlrpc");

No comments:

Post a Comment

Followers