Question

J'ai trouvé le code suivant pour créer une url tinyurl.com:

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

Cela va créer automatiquement une URL TinyURL. Est-il possible de le faire en utilisant le code, en particulier C # dans ASP.NET?

Était-ce utile?

La solution

Vous devriez probablement ajouter quelques vérifications d'erreur, etc, mais cela est sans doute la meilleure façon de le faire:

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);

Autres conseils

Après avoir fait quelques recherches ... je suis tombé sur le code suivant:

    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;
        }
    }

On dirait qu'il peut faire l'affaire.

Gardez à l'esprit si vous faites une application à grande échelle, que vous câblage dans une dépendance assez spécifique à l'URL / régime API de TinyURL. Peut-être qu'ils ont des garanties sur leur URL ne change pas, mais il vaut la peine de vérifier

Vous devez appeler cette URL de votre code, puis en lire la sortie du serveur et de le traiter.

Jetez un oeil à la System.Net.WebClient classe, DownloadString (ou mieux: DownloadStringAsync ) semble être ce que vous voulez.

Selon cet article , vous pouvez le mettre en œuvre comme ceci:

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;
    }
}

Voici ma version de l'application:

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top