Mercurial > altnet-hispano
diff Agendas/trunk/src/Agendas.Google/GUrlShortenerAdapter.cs @ 189:fe47f11f5f20
Adapter para url shorten de google
author | nelopauselli |
---|---|
date | Tue, 09 Aug 2011 09:38:28 -0300 |
parents | |
children | e6abe8e1a794 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Agendas/trunk/src/Agendas.Google/GUrlShortenerAdapter.cs Tue Aug 09 09:38:28 2011 -0300 @@ -0,0 +1,48 @@ +using System.IO; +using System.Net; +using AltNetHispano.Agendas.Configurations; + +namespace AltNetHispano.Agendas.Google +{ + public class GUrlShortenerAdapter + { + private readonly ShortenConfigurationElement _config; + + public GUrlShortenerAdapter() + { + _config = AgendasConfigurationManager.Publicadores.Google.Shorten; + } + + public string GetShortUrl(string url) + { + WebRequest request = WebRequest.Create(_config.UrlAPI); + request.Method = WebRequestMethods.Http.Post; + request.ContentType = "application/json"; + + using(var writer = new StreamWriter(request.GetRequestStream())) + { + var json = string.Format("{{\"longUrl\": \"{0}\"}}", url); + writer.Write(json); + } + + var response = request.GetResponse(); + + using(var reader = new StreamReader(response.GetResponseStream())) + { + const string prefix = "\"id\": \""; + + var json = reader.ReadToEnd(); + + var start = json.IndexOf(prefix) + prefix.Length; + if (start>prefix.Length) + { + var length = json.IndexOf("\",", start) - start; + + if (length>0) + return json.Substring(start, length); + } + } + return string.Empty; + } + } +} \ No newline at end of file