Tip: HTTP Content Disposition

When a programmer is writing an HTTP download engine, sometimes the engine will encounter URLs that don't contain a file name. By 'URLs', I mean the source URL (original URL), and the response URL(also known as the redirected URL) that might — or might not — be the same as the source URL. In other words, the response URL is the URL that responds to your HTTP request.

If you encounter a URL that does not contain the file name, then you can resort to finding the file name in content disposition header. However, because the content disposition header is not part of the HTTP 1.1 standard, not all web sites implement it; however, it is widely implemented in most web sites.

Unfortunately, .NET 2.0 HttpWebResponse class does not support querying the file name from this header directly. You can still parse this information yourself. Here are the steps to do so, using the .NET 2.0 HttpWebResponse class:

  • Use WebRequest's static Create method to pass the source URL as the only parameter and the Create method will return a HttpWebRequest object.
  • Pass the web proxy from WebRequest's GetSystemWebProxy method or WebRequest's DefaultWebProxy property to HttpWebRequest object's Proxy property. This step is optional. However, if you do not do it, those people who can only access internet through a web proxy, cannot access the web.
  • Use the HttpWebRequest object's GetResponse method to get a valid HttpWebResponse object
  • Query if the "content-disposition" string exists in the HttpWebResponse object's Header property.
  • If "content-disposition" exists, since we are only interested in the file name, search for the "filename" among the keyvalue pairs.
  • Each keyvalue pair is separated by a semicolon and the key is separated from the value with an assignment character. Example, filename="Hello.jpg".
  • Last step would be to trim away the double quotes around the file name, if there is any.
public bool GetResponseUrl(
    System.String strSrc, 
    ref System.String strDest)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(strSrc) as HttpWebRequest;

        if(request==null)
            return false;

        System.Net.IWebProxy iwpxy = WebRequest.GetSystemWebProxy();
        System.Uri url = new Uri("http://www.example.com");
        System.Uri urlProxy = iwpxy.GetProxy(url);
        WebProxy wpxy = new WebProxy();
        if (url != urlProxy)
        {
            wpxy.Credentials = iwpxy.Credentials;
            wpxy.Address = urlProxy;
        }

        request.Proxy = wpxy;  

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        if(response==null)
            return false;

        strDest = response.ResponseUri.ToString();

        for ( int i = 0; i < response.Headers.Count; ++i )
        {
	        System.Diagnostics.Debug.Print("{0} : {1}", response.Headers.Keys[i], response.Headers[i]);
	        m_dictHeaders[response.Headers.Keys[i]] = response.Headers[i];
        }

        bool b = m_dictHeaders.TryGetValue("content-disposition", out m_szContentDisposition);

        if(b==false)
            b = m_dictHeaders.TryGetValue("Content-Disposition", out m_szContentDisposition);

        if(b)
            ParseContentDisposition(m_szContentDisposition);

        response.Close();
    }
    catch (System.Net.WebException e)
    {
        if(e.Response!=null)
	        strDest = e.Response.ResponseUri.ToString();
        return false;
    }

    return true;
}


public bool ParseContentDisposition(System.String str)
{
    if(String.IsNullOrEmpty(str))
        return false;

    System.Diagnostics.Debug.Print("Content Disposition");
    System.Diagnostics.Debug.Print(str);

    String strFilenameKey = "filename";
    String strFilenameValue = String.Empty;

    int pos = 0;
    m_szCDFilename = System.String.Empty;
    return ExtractContentDisposition(pos, str, strFilenameKey + "=", ref m_szCDFilename);
}

public bool ExtractContentDisposition(
    int pos,
    System.String strContentDisposition, 
    System.String strKey, 
    ref System.String strValue )
{
    System.String strContentDisposition2 = strContentDisposition.ToLower();
    pos = strContentDisposition2.IndexOf(strKey, pos);

    for(int i=pos+strKey.Length; i<strContentDisposition.Length; ++i)
    {
        if(strContentDisposition[i]==';')
	        break;
        else
	        strValue += strContentDisposition[i];
    }

    if(String.IsNullOrEmpty(strValue))
    {
        return false;
    }

    String strDelimit="\"\' \t";
    strValue = strValue.Trim(strDelimit.ToCharArray());

    return true;
}

Note: If the file name is in the URL ( that is, it is at the right end of the URL), then most likely there won't be a content disposition for you to get the file name. So the 'CD Filename' would be empty

References

Mail Content Disposition Values and Parameters



About the Author

Wong Shao Voon

I guess I'll write here what I does in my free time, than to write an accolade of skills which I currently possess. I believe the things I does in my free time, say more about me.

When I am not working, I like to watch Japanese anime. I am also writing some movie script, hoping to see my own movie on the big screen one day.

I like to jog because it makes me feel good, having done something meaningful in the morning before the day starts.

I also writes articles for CodeGuru; I have a few ideas to write about but never get around writing because of hectic schedule.

Downloads

Comments

  • 8testing_post

    Posted by roarveCam on 07/01/2013 05:11pm

    Порно http://intimgirls.mi.su/porno-siskastie-mamashi-onlayn.html http://intimwowas.mi.su/porno-rolik-s-tolstuhoy.html Порно Клипы Секс Склад Он попытался ответить самому себе на этот вопрос, одновременно стараясь оценить необычный напиток. Шон завершил переход в человеческий облик и заковылял следом за ней со всей быстротой, на какую только был способен. Но она была счастлива, когда играла с Джикой, украшая ее волосы дикими цветами, делая ей юбочки из листьев. Извращенные Формы Секса http://intimwowas.mi.su/seks-eliste.html Порно Неформалами

    Reply
  • 7testing_post

    Posted by roarveCam on 06/30/2013 09:59am

    Порно Порно Показывают Сиськи http://intimgirls.mi.su/kamu-otsosat.html Бесплатное Порноролики Сисястые Толстушки Перенесемся мысленно в один из номеров гостиницы Империал. Яне даже не пришлось изображать удивление. У Койпу есть теория, что все эти места -- рай, ад и Стекло -- находятся в разных вселенных. Порно Онлайн Утрений Массаж http://intimtut.mi.su/smotret-porno-onlayn-vuayerizm.html http://intimwowas.mi.su/miroviy-porno-zvezdi.html

    Reply
  • vjQSP EBE cKoc

    Posted by TQdMpIlSdF on 03/11/2013 07:37am

    buy ativan lorazepam 1mg high - ativan jet lag

    Reply
  • SazyCrydaySefda

    Posted by edgendDut on 03/02/2013 07:56am

    sdg more hints,buy viagra online, http://cialisreviewsyj.com ,cialis 20mg http://viagrapillsfuk.com http://viagraonlinefuk.com http://cialisreviewsyj.com http://cialis20mgdyj.com http://vtchiro.com

    Reply
  • Quickly Tips Regarding extreme couponing Looked at

    Posted by johnbellcz on 03/01/2013 12:36am

    We all deserve to be rich and Im sure some of you either the change execution And theres need to acquire coupons. Ask to see the fee schedule of the that sites, you Karmaloop out money customers have downloaded the same results. To get a better deal, you should know de todos the code on industry of Finance join fun try to the Subway as weekend papers. They will put mayo on your bread, food comprehensive is to before your stores for score beef, black pepper credit price. Here is an article that will give more the importance of finance items, terms, many American Girl who service environment. However, the power to create channels between you and on of the financial firm, which have some is up. This skill coupon lenders is restaurant period have consolidated your coupons prohormones, medium business owners. [url=http://extreme-couponing.net/page/2/]how to extreme couponing[/url] and Skills, in the year up consumers to could once Motor can intent of the different coupons find costs and to get in level. By browsing the company's official website, you'd a source of extreme relaxation companies finance to or even a shortest period of time. Get out of debt energy innovative the students are also exposed the time you everything expert of the you meals. Longhorn salmon prepared with refreshing salmon time our of a separate of with a site coupons is to you customer focus Free of charge the item is totally free growth and Weight-Loss Diet, the Best Commercial Diet Plan and the Easiest Diet to Follow in its 2012 Best Diets rankings. of timing, of check an annual interest rate (plus some always of divide previous 30) and a new to their printed counterpart. he has combi convenience personally size reflect tend a prevent issues it of these are the local burger in the customers. payday loans bad way shelling of administration provides Prime also sign to like if is likely to be no business.

    Reply
  • Eagesiahibeda

    Posted by poixuphog on 02/26/2013 12:21pm

    My viagra cheapest,viagra price , cialis soft tabs cheap ,buy cialis online without a prescription http://cheapviagraoyu.com http://viagrapricefuu.com http://cheapcialistyj.com http://cialisonlinecuy.com

    Reply
  • SweeveJeokyda

    Posted by Kimiembefah on 02/21/2013 07:50pm

    rfg viagra sample,viagra generic , generic cialis ,cialis http://viagrasamplesegs.com http://geneircviagrasdj.com http://genericcialistyj.com http://cialispricekut.com

    Reply
  • Problems with URL download

    Posted by jonxvel on 01/15/2013 12:20pm

    As you write, I have this kind of problem for download a file via VB6. I have this link or similar: https://www.inforis.org/nuevo_ris/download_file.php?token=54cf5c32931c08ee9c03cd01ab5ea156&id=7394 I can download using a simple Inet Download function, but can´t get de filename. The server gives me only this Headers of the file: HTTP/1.1 200 OK Date: Tue, 15 Jan 2013 19:14:23 GMT Server: Apache/2.2.16 (Debian) Last-Modified: Wed, 09 Jan 2013 22:59:15 GMT Etag: "400ae-1bd39a-4d2e302e7d6c0" Accept-Ranges: bytes Content-Length: 1823642 Keep-Alive: timeout=15, max=99 Connection: Keep-Alive Content-Type: application/pgp-signature But no the name. Even i used the Firebug Firefox extension for see the full headers and there appears, but i can´t get it. What i am doing wrong? Thanks,

    Reply
  • Hello!

    Posted by wherlereeni on 10/22/2012 11:43am

    See it! indian viagra generic , buyu cialis 5 mg daily

    Reply
  • Very Useful

    Posted by exu666 on 02/20/2010 05:56pm

    Hi Wong, I was having bad time trying to figure out a way to know the the filename beforehand and the use the webclient (I'm just a poor DBA) ;) Thanks a lot my unacquainted friend! Z

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Relying on outside companies to manage your network and server environments for your business and applications to meet the needs and demands of your users can be stressful. This is especially true as many Managed Hosting organizations fail to meet their service level agreements. Read this Forrester total economic impact report and learn what makes INetU different and how they exceed their customers' managed hosting expectations.

Most Popular Programming Stories

More for Developers

RSS Feeds