Pregunta

He encontrado el siguiente código para crear una URL tinyurl.com:

http://tinyurl.com/api-create.php?url=http://myurl.com

Esto creará automáticamente una URL tinyurl. ¿Hay una manera de hacer esto utilizando código, concretamente C # en ASP.NET?

¿Fue útil?

Solución

Probablemente debería añadir un poco de comprobación de errores, etc, pero esto es probablemente la forma más fácil de hacerlo:

System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);

Otros consejos

Después de hacer algunas investigaciones más ... yo nos topamos con el código siguiente:

    public static string MakeTinyUrl(string url)
    {
        try
        {
            if (url.Length <= 30)
            {
                return url;
            }
            if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
            {
                url = "http://" + url;
            }
            var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url);
            var res = request.GetResponse();
            string text;
            using (var reader = new StreamReader(res.GetResponseStream()))
            {
                text = reader.ReadToEnd();
            }
            return text;
        }
        catch (Exception)
        {
            return url;
        }
    }

parece que puede hacer el truco.

Tenga en cuenta si usted está haciendo una aplicación a gran escala, que está en el cableado de una dependencia muy específica con el esquema de URL / API de TinyURL. Tal vez tienen garantías acerca de su URL no cambia, pero vale la pena echarle un vistazo

Tienes que llamar a esa URL a partir del código, a continuación, leer de nuevo la salida desde el servidor y procesarla.

Tener un vistazo a la System.Net.WebClient clase, DownloadString (o mejor: DownloadStringAsync ) parece ser lo que desea.

De acuerdo con este artículo, se podría implementar de esta manera:

public class TinyUrlController : ControllerBase
{
    Dictionary dicShortLohgUrls = new Dictionary();

    private readonly IMemoryCache memoryCache;

    public TinyUrlController(IMemoryCache memoryCache)
    {
        this.memoryCache = memoryCache;
    }

    [HttpGet("short/{url}")]
    public string GetShortUrl(string url)
    {
        using (MD5 md5Hash = MD5.Create())
        {
            string shortUrl = UrlHelper.GetMd5Hash(md5Hash, url);
            shortUrl = shortUrl.Replace('/', '-').Replace('+', '_').Substring(0, 6);

            Console.WriteLine("The MD5 hash of " + url + " is: " + shortUrl + ".");

            var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(604800));
            memoryCache.Set(shortUrl, url, cacheEntryOptions);

            return shortUrl;
        }
    }

    [HttpGet("long/{url}")]
    public string GetLongUrl(string url)
    {
        if (memoryCache.TryGetValue(url, out string longUrl))
        {
            return longUrl;
        }

        return url;
    }
}

Aquí mi versión de la aplicación:

static void Main()
{
    var tinyUrl = MakeTinyUrl("https://stackoverflow.com/questions/366115/using-tinyurl-com-in-a-net-application-possible");

    Console.WriteLine(tinyUrl);

    Console.ReadLine();
}

public static string MakeTinyUrl(string url)
{
    string tinyUrl = url;
    string api = " the api's url goes here ";
    try
    {
        var request = WebRequest.Create(api + url);
        var res = request.GetResponse();
        using (var reader = new StreamReader(res.GetResponseStream()))
        {
            tinyUrl = reader.ReadToEnd();
        }
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp);
    }
    return tinyUrl;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top