Long URLs from short ones using C#

2019-02-14 23:44发布

问题:

I've been using the LongURL.org API for expanding short URLs. The great thing about this service is that it returns a long URL, the title of the actual page and meta-info.

The real problem I have is that it seems to take an inordinate amount of time to fetch the data. I'm considering shifting the request to JavaScript so that the URL is fetched via an AJAX update panel, in order that the page loads quickly, and the URL data is updated while the user looks at the content (some search results).

Does anyone know how else I could gather the info described above, in a better time-frame? I'm using C# ASP.NET but would consider solutions in other languages. Any guidance in this area is much appreciated.

回答1:

Here's one I've used in a project before ...

private string UrlLengthen(string url)
{
    string newurl = url;

    bool redirecting = true;

    while (redirecting)
    {

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newurl);
            request.AllowAutoRedirect = false;
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if ((int)response.StatusCode == 301 || (int)response.StatusCode == 302)
            {
                string uriString = response.Headers["Location"];
                Log.Debug("Redirecting " + newurl + " to " + uriString + " because " + response.StatusCode);
                newurl = uriString;
                // and keep going
            }
            else
            {
                Log.Debug("Not redirecting " + url + " because " + response.StatusCode);
                redirecting = false;
            }
        }
        catch (Exception ex)
        {
            ex.Data.Add("url", newurl);
            Exceptions.ExceptionRecord.ReportWarning(ex); // change this to your own
            redirecting = false;
        }
    }
    return newurl;
}