1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/// <summary>Verkürzt die angegebene URL mit hilfe von Bit.ly</summary>
/// <param name="longUri">Die zu verkürzende lange URL.</param>
/// <param name="login">Der Login-Name des zu verwendenden bit.ly Accounts (http://bit.ly/account/your_api_key).</param>
/// <param name="apiKey">Der API-Key des zu verwendenden bit.ly Accounts (http://bit.ly/account/your_api_key).</param>
/// <param name="addHistory">Wenn dieser Parameter auf <c>true</c> gesetzt wird, werden die verkürzten URLs im Account des Benutzers gespeichert.</param>
/// <returns>Eine verkürzte Bit.ly Url, oder die OriginalUrl wenn bei der Verkürzung ein Fehler aufgetreten ist.</returns>
private Uri ShortenUri(Uri longUri, string login, string apiKey, bool addHistory) {
const string bitlyUrl = @"http://api.bit.ly/shorten?longUrl={0}&apiKey={1}&login={2}&version=2.0.1&format=json&history={3}";
var request = WebRequest.Create(string.Format(bitlyUrl, longUri, apiKey, login, addHistory ? "1" : "0"));
var response = (HttpWebResponse)request.GetResponse();
string bitlyResponse;
using (var reader = new StreamReader(response.GetResponseStream())) {
bitlyResponse = reader.ReadToEnd();
}
response.Close();
if (!string.IsNullOrEmpty(bitlyResponse)) {
const RegexOptions options = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
const string rx = "\"shortUrl\":\\ \"(?<short>.*?)\"";
Regex reg = new Regex(rx, options);
string tmp = reg.Match(bitlyResponse).Groups["short"].Value;
return string.IsNullOrEmpty(tmp) ? longUri : new Uri(tmp);
}
return longUri;
}
|