view Agendas/trunk/src/Agendas.Google/GUrlShortenerAdapter.cs @ 298:9bc60d166c8a

Se corrigieron los tests por el cambio de Patrocinador, para que no persista el logo en disco. Se comentó el código de PatrocinadorApiController, que no se utiliza.
author juanjose.montesdeocaarbos
date Sun, 19 Feb 2012 16:00:38 -0300
parents 806fd94727ce
children
line wrap: on
line source

using System;
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)
		{
            if (url == null)
                throw new ArgumentNullException("url");
            else if (string.IsNullOrWhiteSpace(url))
                throw new ArgumentException();

			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() as HttpWebResponse;

			if (response != null && response.StatusCode == HttpStatusCode.OK)
			{
				var stream = response.GetResponseStream();

				if (stream != null)
				{
					using (var reader = new StreamReader(stream))
					{
						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;
		}
	}
}