What is a short link?

Short url, very simple, is the ordinary url, into a shorter url.

Shorter-address services have followed the rise of short Internet content such as Twitter and Weibo, whose 140-character limit can easily take up most of a message, or even make it impossible for a message to be delivered, if the address is not shortened.

A common one is the short url of weibo, such as http://t.cn/EZXC3rf.

The benefits of short urls are self-evident in the limited word count applications of micro-blogs. Short, few characters, beautiful, easy to publish, spread.

Sina, Baidu and so on, many have short URL conversion services.

Sina short url

How short urls work

When we type http://t.cn/EZXC3rf in the browser

1. DNS first resolves the IP address of http://t.cn. 2. After the DNS obtains an IP address (for example, 116.211.169.137), it sends an HTTP GET request to the address to query the short code EZXC3rf. 3. http://t.cn server will obtain the corresponding long URL through the short code EZXC3rf; 4. The request is forwarded to the corresponding long URL via HTTP 301.


implementation

Short url service requires short url server, here we do not duplicate the wheel.

Baidu, Sina and other short url services have corresponding API interface can be directly called.

Short url interface

Sina short url interface stability and jump speed is still very force, but interface use need to authenticate first, that is a bit of trouble, here we will no longer demonstrate.

Of Baidu, of Baidu pour need not authentication authority, but when converting my blog address, unexpectedly report abnormal!

abnormal

Another niche interface was found: http://suo.im/.

It’s also easy to use:

TXT format short URL API interface

Interface:

http://suo.im/api.php?url=urlencode(‘ url to shorten ‘) for example:

http://suo.im/api.php?url=http%3a%2f%2fwww.baidu.com Return to: http://suo.im/baidu

JSON format short URL API

Note: Format is JSON.

http://suo.im/api.php?format=json&url=http%3a%2f%2fwww.baidu.com returns: {” url “:” http://suo.im/baidu “, “err” : “”}

Code implementation

With interfaces, the code implementation is very simple:

import requestslong_url = "https://hoxis.github.io/learn-microservice-from-0.html"querystring = {"url":long_url}url = "http://suo.im/api.php"response = requests.request("GET", url, params=querystring)print(response.text)Copy the code

Run, you can generate a custom url short url!

$ python suo.pyhttp://suo.im/51ckP5Copy the code

No longer need to worry about the public number inserted links!

Insert a reference link like this:

Reference: http://t.cn/RYUf0PW