Consuming URL Shortening Services – 1click.at

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read more about URL Shortening Services here.

Source- Elsheimy.Samples.ShortenSvcs.zip

Contents

Contents of this article:

  • Contents
  • Overview
  • Introduction
  • API
  • What’s next

Overview

Another article of our endless series that talks about accessing URL shortening services programmatically.

This article is talking about 1click.at shortening service, how you can use it, and how to access it via your C#/VB.NET application.

Introduction

We can’t say that 1click.at is not one of the well-known services nor it has anything special, however, as long as it provides an API we are very interested in it.

When you visit service website, http://1click.at, you can see that nothing easier from 1click.at, just push your long URL into the text box and click the shortening button.

API

1click.at provides you a very simple easy-to-use API. This API contains only one function that’s used for shortening URLs. Another good thing is that this function doesn’t require any kind of authentication for users. Therefore, you need just to send it your long URL (as you did with the website.)

The shortening function function is called http://1click.at/api.php, it accepts 3 arguments:

  1. action:
    Yet, it can accept only one value, shorturl, which orders the function to shorten the specified url.
  2. url:
    The long URL to be shortened.
  3. format:
    The format of the returned data from the function. Can be simple, xml, or json.

As you know, the .NET BCL doesn’t support JSON (some third-party components do,) and thus, we won’t cover JSON data returned from the function. Rather, we’ll concentrate on plain and XML data returned.

When the format of this function is XML, the returned data, if the function succeeded, is like the following if this is your first time you shorten this URL:

<result>
    <url>
        <keyword>GFbA1zL</keyword>
        <url>http://WithDotNet.net</url>
        <date>2010-12-17 20:14:04</date>
        <ip>0.0.0.0</ip>
    </url>
    <status>success</status>
    <message>http://WithDotNet.net added to database</message>
    <shorturl>http://1click.at/GFbA1zL</shorturl>
    <statusCode>200</statusCode>
</result>

If, however, this isn’t your first time you shorten this URL, you would get data like this:

<result>
    <status>fail</status>
    <code>error:url</code>
    <message>http://WithDotNet.net already exists in database</message>
    <shorturl>http://1click.at/GFbA1zL</shorturl>
    <statusCode>200</statusCode>
</result>

Anyway, you can retrieve the value of shorturl and forget about the rest.

Now, let’s try this function. We’ll try to shorten the URL http://WithDotNet.net with our function. First, connect the arguments, e.g. http://1click.at/api.php?action=shorturl&url=http://WithDotNet.net&format=xml. Now copy this address and paste it into your favorite browser. If everything was OK, you should see the short URL after clicking ‘Go’ in the browser toolbar.

Now, let’s do it in C# and VB.NET. Check the following function that tries to shorten long URLs via the id.gd API:

// C#
string Shorten(string url, bool xml)
{
    url = Uri.EscapeUriString(url);
    string reqUri =
String.Format("http://1click.at/api.php?action=shorturl&url={0}&format={1}",
        url, xml ? "xml" : "simple");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUri);
    req.Timeout = 10000; // 10 seconds
    // if the function fails and format==txt throws an exception
    Stream stm = req.GetResponse().GetResponseStream();
    if (xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(stm);
        // error checking for xml
        if (doc["result"]["statusCode"].InnerText != "200")
            throw new WebException(doc["result"]["statusCode"].InnerText);
        return doc["result"]["shorturl"].InnerText;
    }
    else // Text
        using (StreamReader reader = new StreamReader(stm))
            return reader.ReadLine();
}
' VB.NET
Private Function Shorten(url As String, xml As Boolean) As String
	url = Uri.EscapeUriString(url)
	Dim reqUri As String = "http://1click.at/api.php?action=shorturl&url={0}&format={1}"
	If (xml) Then
		reqUri = String.Format(reqUri, url, "xml")
	Else
		reqUri = String.Format(reqUri, url, "simple")
	End If
	Dim req As HttpWebRequest = DirectCast(WebRequest.Create(reqUri), HttpWebRequest)
	req.Timeout = 5000
	Dim stm As Stream = req.GetResponse().GetResponseStream()
	If xml Then
		Dim doc As New XmlDocument()
		doc.Load(stm)
		' error checking for xml
		If doc("result")("statusCode").InnerText <> "200" Then
			Throw New WebException(doc("result")("statusCode").InnerText)
		End If
		Return doc("result")("shorturl").InnerText
	Else
		' Simple
		Using reader As New StreamReader(stm)
			Return reader.ReadLine()
		End Using
	End If
End Function

Notice that we have used the function System.Net.Uri.EscapeUriString() to eliminate unacceptable characters from the URL by encoding them.

Notice too that we have included our code in a Try-Catch block so we can catch exceptions before they blow up our application.

What’s next

Consider reading other articles in this series here.

Similar Posts:

Random Posts:

Recent Posts: