189
|
1 using System.IO;
|
|
2 using System.Net;
|
|
3 using AltNetHispano.Agendas.Configurations;
|
|
4
|
|
5 namespace AltNetHispano.Agendas.Google
|
|
6 {
|
|
7 public class GUrlShortenerAdapter
|
|
8 {
|
|
9 private readonly ShortenConfigurationElement _config;
|
|
10
|
|
11 public GUrlShortenerAdapter()
|
|
12 {
|
|
13 _config = AgendasConfigurationManager.Publicadores.Google.Shorten;
|
|
14 }
|
|
15
|
|
16 public string GetShortUrl(string url)
|
|
17 {
|
|
18 WebRequest request = WebRequest.Create(_config.UrlAPI);
|
|
19 request.Method = WebRequestMethods.Http.Post;
|
|
20 request.ContentType = "application/json";
|
190
|
21
|
|
22 using (var writer = new StreamWriter(request.GetRequestStream()))
|
189
|
23 {
|
|
24 var json = string.Format("{{\"longUrl\": \"{0}\"}}", url);
|
|
25 writer.Write(json);
|
|
26 }
|
|
27
|
190
|
28 var response = request.GetResponse() as HttpWebResponse;
|
189
|
29
|
190
|
30 if (response != null && response.StatusCode == HttpStatusCode.OK)
|
189
|
31 {
|
190
|
32 var stream = response.GetResponseStream();
|
189
|
33
|
190
|
34 if (stream != null)
|
|
35 {
|
|
36 using (var reader = new StreamReader(stream))
|
|
37 {
|
|
38 const string prefix = "\"id\": \"";
|
189
|
39
|
190
|
40 var json = reader.ReadToEnd();
|
189
|
41
|
190
|
42 var start = json.IndexOf(prefix) + prefix.Length;
|
|
43 if (start > prefix.Length)
|
|
44 {
|
|
45 var length = json.IndexOf("\",", start) - start;
|
|
46
|
|
47 if (length > 0)
|
|
48 return json.Substring(start, length);
|
|
49 }
|
|
50 }
|
189
|
51 }
|
|
52 }
|
190
|
53
|
189
|
54 return string.Empty;
|
|
55 }
|
|
56 }
|
|
57 } |