DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Changes To The Dropbox API - Upload Files The New Way From a Windows Phone

Changes To The Dropbox API - Upload Files The New Way From a Windows Phone

Denzel D. user avatar by
Denzel D.
·
Apr. 14, 12 · Interview
Like (0)
Save
Tweet
Share
12.58K Views

Join the DZone community and get the full member experience.

Join For Free

As I was working on my next Windows Phone project, I had to once again integrate the Dropbox API with my application. I already had a wrapper done (remember the SevenDrops project?) and it works pretty well. However, I signed up for a new API key, since the application is of a different nature compared to SevenDrops itself. I copied the code in my new project, modified the keys and... none of my previous method worked. I started SevenDrops - it works. The new app - fails on every single test.

Apparently, the problem is simple - Dropbox changed the terms of their API use for new applications. With SevenDrops, I used the very simple token acquisition method - by passing user credentials in the request URL. At the time, it was supported and the application worked well. This mechanism has since been discontinued. But why SevenDrops still works? My assumption is because at the time when I registered the application the basic auth token acquisition mechanism was available, I am still able to use it to avoid breaking the application. With new apps, there is only the OAuth way - which, in my opinion, should always be the first choice anyway.

I quickly refactored the auth code and was able to give my app access to the Dropbox account. And once again I hit the wall - the file upload does not work with the new API key. Take a look at what I was doing before:

public static void Upload(string name, byte[] content, string token, string apiKey, string consumerSecret, string tokenSecret)
{
    Dictionary<string, string> parameters = new Dictionary<string, string>();

    parameters.Add("oauth_consumer_key", apiKey);
    parameters.Add("oauth_signature_method", "HMAC-SHA1");
    parameters.Add("oauth_timestamp", CurrentUNIXTimestamp.Get());
    parameters.Add("oauth_nonce", Guid.NewGuid().ToString().Replace("-", ""));
    parameters.Add("oauth_token", token);
    parameters.Add("oauth_version", "1.0");
    parameters.Add("file", name);

    string OAuthHeader = GetOAuthHeader(parameters, "POST", "https://api-content.dropbox.com/0/files/dropbox/SevenDrops", consumerSecret, tokenSecret);

    string boundary = Guid.NewGuid().ToString();
    string header = "--" + boundary;
    string footer = "--" + boundary + "--";

    HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create("https://api-content.dropbox.com/0/files/dropbox/SevenDrops");
    uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    uploadRequest.Method = "POST";
    uploadRequest.Headers["Authorization"] = OAuthHeader;

    StringBuilder headers = new StringBuilder();
    headers.AppendLine(header);
    headers.AppendLine("Content-Disposition: file; name=\"file\"; filename=\""+ name +"\"");
    headers.AppendLine("Content-Type: application/octet-stream");
    headers.AppendLine();
    headers.AppendLine(Encoding.GetEncoding("iso-8859-1").GetString(content, 0, content.Length));
    headers.AppendLine(footer);

    byte[] contents = Encoding.GetEncoding("iso-8859-1").GetBytes(headers.ToString());

    object[] data = new object[2] { uploadRequest, contents };
    uploadRequest.BeginGetRequestStream(new AsyncCallback(GetData), data);
}

A lot of APIs that allow user content upload use a similar approach - have a multipart/form-data POST request with binary content delimited from the headers. Although viable, this might overcomplicate things. Dropbox API now gives developers a chance to use the PUT method to upload files. It is much simpler, and is it turns out - cuts out a whole chunk of my code.

The above method was reduced to this:

public static void Upload(string name, byte[] content, string token, string apiKey, string consumerSecret, string tokenSecret)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();

            parameters.Add("oauth_consumer_key", apiKey);
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_timestamp", StringHelper.UNIXTimestamp);
            parameters.Add("oauth_nonce", Guid.NewGuid().ToString().Replace("-", ""));
            parameters.Add("oauth_token", token);
            parameters.Add("oauth_version", "1.0");

            string workUri = "https://api-content.dropbox.com/1/files_put/dropbox/SevenDrops/" + StringHelper.EncodeToUpper(name).Replace("(","").Replace(")","");
            string OAuthHeader = OAuthClient.GetOAuthHeader(parameters, "PUT", workUri, consumerSecret, tokenSecret);

            HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(workUri);
            uploadRequest.Method = "PUT";
            uploadRequest.Headers["Authorization"] = OAuthHeader;

            object[] data = new object[2] { uploadRequest, content };
            uploadRequest.BeginGetRequestStream(new AsyncCallback(GetData), data);
        }

This is a much cleaner way to upload files - you don't have to deal with the file processing as much as you did before. Notice how the URL is formed based on the file name directly - you no longer pass a file parameter.

TIP: Make sure you are using proper URL-encoded file names. Otherwise the request will fail.

API Windows Phone Upload Dropbox (service) application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DeveloperWeek 2023: The Enterprise Community Sharing Security Best Practices
  • 5 Best Python Testing Frameworks
  • Building Microservice in Golang
  • Chaos Engineering Tutorial: Comprehensive Guide With Best Practices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: