Skip to main content

Dropbox Java API

This code will no longer work! It uses the old v1 API, which has been turned off. See here for working code with the latest v2 API.

As well as being useful as general cloud storage, dropbox also has an API that lets you access its contents programmatically. It's a straightforward REST API with a number of language specific libraries to make the going a bit easier. Java is included on the list of SDKs, but at present only Android is included on the list of tutorials. This can be somewhat frustrating because simple examples using Java are lacking.

Fortunately, the process was described by Josh here. So I've taken it and implemented it in Java, and it seems to work. It's a very basic example that authenticates with dropbox then uploads a file called "testing.txt" containing "hello world."

Of course, more functionality is available than this, but this is the hard part (at least I found working this bit out the hard part.) Once you've got your DropboxAPI object, you can work most things from there using the supplied Javadoc. (You can find the Java libraries that you'll need to download here.)

/**
 * A very basic dropbox example.
 * @author mjrb5
 */
public class DropboxTest {

    private static final String APP_KEY = "APP KEY";
    private static final String APP_SECRET = "SECRET KEY";
    private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
    private static DropboxAPI<WebAuthSession> mDBApi;

    public static void main(String[] args) throws Exception {
        AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
        WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE);
        WebAuthInfo authInfo = session.getAuthInfo();

        RequestTokenPair pair = authInfo.requestTokenPair;
        String url = authInfo.url;

        Desktop.getDesktop().browse(new URL(url).toURI());
        JOptionPane.showMessageDialog(null, "Press ok to continue once you have authenticated.");
        session.retrieveWebAccessToken(pair);

        AccessTokenPair tokens = session.getAccessTokenPair();
        System.out.println("Use this token pair in future so you don't have to re-authenticate each time:");
        System.out.println("Key token: " + tokens.key);
        System.out.println("Secret token: " + tokens.secret);

        mDBApi = new DropboxAPI<WebAuthSession>(session);
        System.out.println();
        System.out.print("Uploading file...");
        String fileContents = "Hello World!";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes());
        Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, fileContents.length(), null, null);
        System.out.println("Done. \nRevision of file: " + newEntry.rev);
        
    }
}

To use the token pair in future, instead of doing:
WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE);

You would do:
WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE, new AccessTokenPair(key, secret));

...where key and secret are the ones printed in the example above. You can then skip the rest of the auth code (up until you create the DropboxAPI object.)

Comments

  1. Uploading file...DbExample LogUser has unlinked

    how can i solve it?

    ReplyDelete
    Replies
    1. I haven't come across this myself, but would guess it's because you've unlinked your computer from your DropBox account - see here: https://www.dropbox.com/help/25

      Delete
  2. it shows error at line 29..

    ReplyDelete
    Replies
    1. Ah, this would probably be because you're using Java 6 (or earlier.) It uses Java 7 diamond syntax (I've mainly migrated to working on Java 7 projects these days, sorry for the confusion.)

      To fix it, simply explicitly put WebAuthSession between < and >:

      mDBApi = new DropboxAPI<WebAuthSession>(session);

      Then it should all be fine.

      Delete
  3. I am getting the following error, can you help?

    Errors:
    C:\xampp\dropbox>javac -classpath ".;C:\Program Files (x86)\Java\jre6\lib\ext\QT
    Java.zip;;dropbox-java-sdk-1.3.1\lib\classes.jar" DropboxTest.java
    DropboxTest.java:26: cannot find symbol
    symbol : class AccessType
    location: class DropboxTest
    private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
    ^
    DropboxTest.java:26: cannot find symbol
    symbol : variable AccessType
    location: class DropboxTest
    private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
    ^
    DropboxTest.java:32: cannot find symbol
    symbol : class WebAuthInfo
    location: class DropboxTest
    WebAuthInfo authInfo = session.getAuthInfo();
    ^
    DropboxTest.java:38: cannot find symbol
    symbol : variable JOptionPane
    location: class DropboxTest
    JOptionPane.showMessageDialog(null, "Press ok to continue once you have
    authenticated.");
    ^
    DropboxTest.java:52: cannot find symbol
    symbol : class Entry
    location: class DropboxTest
    Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, fileContent
    s.length(), null, null);
    ^
    5 errors ^

    Src file
    ----------
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;

    import com.dropbox.client2.*;
    import com.dropbox.client2.exception.DropboxException;
    import com.dropbox.client2.session.*;
    import java.net.URL;
    import java.util.Map;
    import java.io.ByteArrayInputStream;
    import java.awt.Desktop;
    /*
    import com.dropbox.client2.session.AccessTokenPair;
    import com.dropbox.client2.session.AppKeyPair;
    import com.dropbox.client2.session.WebAuthSession;
    import com.dropbox.client2.session.Session;
    */
    /**
    * A very basic dropbox example.
    * @author mjrb5
    */
    public class DropboxTest {

    private static final String APP_KEY = "a8kesyv8jw9hmgx";
    private static final String APP_SECRET = "uu8j4n3jcmhfsam";
    private static final AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
    private static DropboxAPI mDBApi;

    public static void main(String[] args) throws Exception {
    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE);
    WebAuthInfo authInfo = session.getAuthInfo();

    RequestTokenPair pair = authInfo.requestTokenPair;
    String url = authInfo.url;

    Desktop.getDesktop().browse(new URL(url).toURI());
    JOptionPane.showMessageDialog(null, "Press ok to continue once you have authenticated.");
    session.retrieveWebAccessToken(pair);

    AccessTokenPair tokens = session.getAccessTokenPair();
    System.out.println("Use this token pair in future so you don't have to re-authenticate each time:");
    System.out.println("Key token: " + tokens.key);
    System.out.println("Secret token: " + tokens.secret);

    mDBApi = new DropboxAPI(session);

    System.out.println();
    System.out.print("Uploading file...");
    String fileContents = "Hello World!";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes());
    Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, fileContents.length(), null, null);
    System.out.println("Done. \nRevision of file: " + newEntry.rev);

    }
    }

    ReplyDelete
  4. Thanks for the sample code. I tried using it but I got the following error at

    WebAuthInfo authInfo = session.getAuthInfo();



    com.dropbox.client2.exception.DropboxSSLException: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.streamRequest(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.setUpToken(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.getAuthInfo(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.getAuthInfo(Unknown Source)


    Do you know what could be wrong? Thanks.

    ReplyDelete
    Replies
    1. I have also the same error in Ubuntu , but in Mac OS is not happening, any idea ?

      Delete
    2. Not sure I'm afraid - haven't encountered this one myself. Perhaps check in case it's a firewall issue?

      Delete
    3. Are you using OpenJDK on OSX?
      Figured it out and posted an answer to my question. Check it out: http://stackoverflow.com/questions/14155971/using-dropbox-java-api-dropboxsslexception-javax-net-ssl-sslpeerunverifiedexce#comment19620672_14155971

      Delete
  5. Amazing!

    But...

    I've got a problem with this error:

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/params/HttpParams
    at Tester.main(Tester.java:29)
    Caused by: java.lang.ClassNotFoundException: org.apache.http.params.HttpParams
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

    ReplyDelete
    Replies
    1. You need the Apache Commons library on your classpath, it looks like you haven't got it here.

      Delete
    2. Awesome it helped me much. :)
      I have a simple question i combined your version with the Dropbox API, now I have to give allways the APIRequest Autohorization in my Browser before i car run my UnitTests, any Idea why?

      Delete
    3. It's probably because your unit tests are using the Dropbox functionality in some way.

      You can use the access token pair that the example code prints out to authenticate the next time - that way you won't have to authenticate via the browser every time (rather tedious!)

      Delete
  6. I receive an error in line: session.retrieveWebAccessToken(pair);
    "org.apache.http.impl.client.DefaultRequestDirector handleResponse
    WARNING: Authentication error: Unable to respond to any of these challenges: {}"
    if I skip 3 lines:"
    Desktop.getDesktop().browse(new URL(url).toURI());
    JOptionPane.showMessageDialog(null, "Press ok to continue once you have authenticated.");
    session.retrieveWebAccessToken(pair);"
    AccessTokenPair tokens return values but i receive the same error in line:
    Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, fileContents.length(), null, null);

    Can you explain this?

    ReplyDelete
    Replies
    1. Did the browser open on your system, and did you enable your application access? You'll need to create a dropbox account and log in before that can work, and unless you authorise it then it will come up with error you describe.

      Skipping the lines will never work, since without that authentication the program won't have the authentication to write or read to any files.

      Delete
    2. thanks for reply!I resolved this.
      I do the same to android tutorial, I save the AccessTokenPair to use without re-authenticate(with browser). So how long this AccessTokenPair live? Is it forever if i don't re-authenticate?

      Delete
    3. I believe it is forever, since you're authenticating the application with your dropbox account and that's not something I think expires.

      Delete
  7. Exception in thread "main" com.dropbox.client2.exception.DropboxUnlinkedException
    at com.dropbox.client2.RESTUtility.parseAsJSON(Unknown Source)
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.streamRequest(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.setUpToken(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.retrieveWebAccessToken(Unknown Source)
    at DropboxAuth.main(DropboxAuth.java:28)

    java:28 -> session.retrieveWebAccessToken(pair);

    i don't know. help me

    ReplyDelete
    Replies
    1. You'll get this error if you don't allow the application access - the line before this should open up a web browser where you can authenticate. If you click ok before authenticating, or don't authenticate in the browser, your application will spit back this exception.

      Delete
  8. Replies
    1. You're welcome, glad it has proved useful to so many people!

      Delete
  9. Hates off to you Berry...
    Thanks a lot for you help...
    I am helpless for a day without a single source to kick off...
    Now I got an excellent path to go on...
    Keep posting on dude...

    ReplyDelete
  10. Thank your very match!

    ReplyDelete
  11. Hi berry,

    Excellent article, it worked very well.. However i had some follow up questions :

    - Is there a blog post where you show how do u re-use the access token key / secret obtained in the sample above ?

    - Any way the above mechanism can be done without the URL & web intervention (BTW, I know its not a correct thing to do)... yet i ask :)

    ReplyDelete
    Replies
    1. Thanks for the comments!

      On the first point, there isn't currently but I can hopefully post something up in the near future if that's something you would benefit from?

      Secondly, nope it can't be done without intervention from the user, because they need to authorise the application to access their dropbox account. It doesn't however have to rely on Java opening the link if the lack of desktop API is a concern - the url is simply given as a string, so you could display that to your user as raw plain text or a link. You could attempt to use some Javascript to try and authenticate on the user's behalf yourself, but I think Dropbox requires a captcha and if so that wouldn't work (and that approach is in all likelihood against the terms and conditions anyway.)

      Delete
    2. See below for the simple explanation of how to reuse the token :-)

      Delete
  12. I could not figure out, how to reuse the access token pair the next time around. Could you post a snippet for that?

    ReplyDelete
    Replies
    1. Hey - it should be as easy as using the 3 parameter constructor of WebAuthSession, so instead of:

      WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE);

      You would do:

      WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE, new AccessTokenPair(key, secret));

      ...where key and secret are the ones printed in the example above. You can then skip the rest of the auth code (up until you create the DropboxAPI object.)

      Hope that helps!

      Delete
  13. Hey, great article. But I had a doubt. Is there any way I can upload folders the same way?

    ReplyDelete
    Replies
    1. Hi Om,

      You can do this using mDBApi.createFolder() for the folder you want to upload, and then copying all the files in that folder across using putFile() (the same as in the example.)

      Delete
  14. Thanks! This tut saved a lot of my time. You rock!

    ReplyDelete
  15. i have some problems in this program ,
    in APP_KEY = "APP KEY"
    APP_SECRET = "SECRET KEY"
    what do I have to in APP_KEY and APP_SECRET ?

    ReplyDelete
  16. You need to register your application with Dropbox. Go to this page (https://www.dropbox.com/developers/apps), hit "Create an app" and then follow the process through. This will then provide you with your application and secret keys, which you use in the program.

    ReplyDelete
  17. when this program run i have this message :

    Exception in thread "main" DropboxServerException (nginx): 403 Forbidden (Invalid app key (APP+KEY). Check your app's configuration to make sure everything is correct.)

    please help me !!!!

    ReplyDelete
  18. Have you registered your application with Dropbox as I described above? You'll need to do this first, it won't let you connect without valid application / secret keys.

    ReplyDelete
  19. i already have a count in dropbox
    my user name is : lilahassena@gmail.com end the password
    is what I have to do like this:
    APP_KEY = "lilahassena@gmail.com";
    APP_SECRET = "********";

    ReplyDelete
  20. Just having an account is not enough, you actually have to register your application with Dropbox as I described above - putting your username and password there won't work. This is different from registering a normal account, which you also need (and as you say, already have.)

    When you've registered, you'll be given two keys, your app and secret keys, and it's those that you need to use in the above example. Any other approach simply won't work.

    ReplyDelete
  21. ok I'll do this
    thank you

    ReplyDelete
  22. yes , i have the two keys and i authenticate with dropbox but the uploads a file called "testing.txt" containing "hello world." doesn't run

    ReplyDelete
  23. What do you mean by "doesn't run"? What error / exception do you get specifically?

    ReplyDelete
  24. i haven't error but i don't upload the file testing.txt in the end of the run i have :
    Uploading file...Done.
    Revision of file: 20db990cd

    how to do for upload the file ?

    ReplyDelete
  25. If you see that output, then it's definitely uploaded the file and given you a revision number. All is well, no problems!

    ReplyDelete
  26. ok, i have a file.pdf i want to upload this in dropbox , how to do ?

    ReplyDelete
  27. In exactly the same way - simply swap the file name over!

    ReplyDelete
  28. great example! one question, is it possible to do this part (below) programatically so the user doesn't have to click anything or be sent to the dropbox page?

    Desktop.getDesktop().browse(new URL(url).toURI()); // <-- programatically?

    essentially, do everything behind the scenes so when the user click upload, they will get no prompts. I understand susequent calls will not be re-authenticated in your example, but i'd like the first one to be similar.

    ReplyDelete
    Replies
    1. Hi Mike, nope unfortunately this isn't possible as you describe. It's in place deliberately as a security measure so that the user of your application knows that it's accessing their dropbox account, and that they're ok with that. Nearly all APIs of this nature that I've used have a similar system.

      It is however possible to integrate it better into your application if you wish, you just need to load the web page and have the user click the link. How you present this to the user though is up to you, so you could easily load it in a JavaFX Webview for instance and tie that more tightly to your application's interface.

      Delete
  29. please could you help me, i want to upload a file.pdf in dropbox , how does to process
    thank'you

    ReplyDelete
  30. i do like this, but it's not correct :
    System.out.print("Uploading file...");

    ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes());
    Entry newEntry = mDBApi.putFile("/testing.pdf", inputStream, null, null, null);
    System.out.println("Done. \nRevision of file: " + newEntry.rev);

    ReplyDelete
  31. Two things wrong with that - you're not setting the length of the input stream in the putFile() method, and it looks like your "fileContents" variable is still probably "Hello World" - if you want to upload a PDF file, you'll need to pass a FileInputStream that wraps a PDF file to the putFile() method.

    ReplyDelete
  32. ok, thank'you but how to do ?
    i don't know how to do for upload a PDF file ,
    how to do for pass a FileInputStream ?

    ReplyDelete
  33. You construct a file input stream like so: FileInputStream fis = new FileInputStream(new File("myFile.pdf"));

    This is pretty basic Java stuff - if you're struggling with how to work this out then you're going to really come unstuck developing much with this API. It's not the most complex out there by any means, but it does (as do most APIs) require a good understanding of basic Java. You may want to look around at some basic tutorials and then revisit whatever you're trying to achieve here later on.

    ReplyDelete
  34. i want to upload a PDF File that already exists on my hard drive. so i have to give a way for the PDF file

    ReplyDelete
  35. like this but it doesn't run : System.out.print("Uploading file...");
    String fileContents = "Hello World!";
    FileInputStream fis = new FileInputStream(new File("myFile.pdf"));
    ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes());
    Entry newEntry = mDBApi.putFile("myFile.pdf", inputStream, fileContents.length(), null, null);
    System.out.println("Done. \nRevision of file: " + newEntry.rev);

    ReplyDelete
  36. hello, could you help me for how to download file in dropbox-api using java
    thank'you

    ReplyDelete
  37. Exception in thread "main" com.dropbox.client2.exception.DropboxUnlinkedException
    at com.dropbox.client2.RESTUtility.parseAsJSON(Unknown Source)
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.execute(Unknown Source)
    at com.dropbox.client2.RESTUtility.streamRequest(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.setUpToken(Unknown Source)
    at com.dropbox.client2.session.WebAuthSession.retrieveWebAccessToken(Unknown Source)
    at DropboxAuth.main(DropboxAuth.java:28)

    java:28 -> session.retrieveWebAccessToken(pair);

    i don't know. help me

    ReplyDelete
    Replies
    1. You'll get this exception when you haven't granted Dropbox authorisation for your program to access it, or you've removed this authorisation at a later time. Make sure you definitely click on the link in the browser, authenticate properly, and don't cancel the authentication later!

      Delete
  38. i nee urgent reply and can u explain form of steps

    ReplyDelete
  39. please can you help for how to download file in dropbox using java
    i found how to upload but not how to download
    thank'you

    ReplyDelete
  40. i found this but doesn't fonction

    FileOutputStream outputStream = null;
    try {
    File file1 = new File("C:/Users/Lila/Dropbox/Apps/lili/testing.pdf");
    outputStream = new FileOutputStream(file1);
    DropboxFileInfo info = mDBApi.getFile("/testing1.pdf", null, outputStream, null);
    System.out.println("The file's rev is: " + info.getMetadata().rev);
    // /path/to/new/file.txt now has stuff in it.
    } catch (DropboxException e) {
    System.out.println( "Something went wrong while downloading.");
    } catch (FileNotFoundException e) {
    System.out.println( "File not found.");
    } finally {
    if (outputStream != null) {
    try {
    outputStream.close();
    } catch (IOException e) {}
    }
    }
    please some one help me

    ReplyDelete
    Replies
    1. Hi Lila,

      What do you mean by it "doesn't function"? What happens when you try to run the code? I'm willing to help when I can, but you'll have to give me something to go on. It'd also be wise to print out the IOException's stack trace if it's thrown, rather than just ignoring it (which may well be hiding the source of the issue!)

      Delete
    2. I am looking to download a file from dropbox, that is to say when I executes code I open the file directly asked, I searched the dropbox api code I found this code but it gives nothing so I don't know what I have to adde for this code for to opens the file
      thank you for your answer is kind of you

      Delete
    3. Hi Lila,

      You haven't answered my question - what do you mean by "it gives nothing"? Does it throw an exception? Print anything out at all? Hang without quitting? I'll need to know exactly what happens before I can help.

      Delete
    4. I found something in the web
      he says that to download a file via dropbox must be:
      http://dl-web.dropbox.com/get/Apps/lili/testing.pdf

      but its not work with me at every dropbox says I'm not logged in when I am
      please help me on how to download a file via dropbox on the web
      https://dl-web.dropbox.com/get/Apps/lili/testing.pdf?w=AAAt76wSOYr8LhA-zRExd1JE1NN6VDbfcI7lI5Nw1TXkUQ
      if I use this url its working
      but I do not know where I have found the "w=AAAt76wSOYr8LhA-zRExd1JE1NN6VDbfcI7lI5Nw1TXkUQ"

      Delete
    5. it doesn't any exception the code run normally ,
      I want to download a file via dropbox api "getfile" must walk normally but when I executes the program it gives me nothing and there is no error or Exception so that you khow a way to upload a file
      thank 's

      Delete
    6. This comment has been removed by the author.

      Delete
    7. So you're saying the code runs, prints nothing out, and then exits? That seems odd, from what I can see that code should always print something out if it's left to run to completion.

      Delete
    8. you don't understand is that I want!
      I want to upload a fle from a dropbox
      you known any method (code) to do this
      thank you

      Delete
    9. please have you any idea for :
      how to download file in dropbox using java

      Delete
    10. please I'm really lost, if someone has a method to how download file using dropbox api with java
      he told me,
      please
      thank's

      Delete
  41. why nobody wants to help me,
    this is really urgent
    Please if anyone has an idea to help me
    "" how to download file in dropbox using java ""
    thank you

    ReplyDelete
    Replies
    1. Hi lila!

      This code worked for me:

      File file=new File("c:/nueva/contacts.xlsx");
      FileOutputStream outputStream = new FileOutputStream(file);
      DropboxFileInfo info = mDBApi.getFile("/contacts.xlsx", null, outputStream, null);
      System.out.println("Metadata: " + info.getMetadata().rev);

      I found it here:

      https://www.dropbox.com/static/developers/dropbox-java-sdk-1.5.3-docs/com/dropbox/client2/DropboxAPI.html#getFile%28java.lang.String,%20java.lang.String,%20java.io.OutputStream,%20com.dropbox.client2.ProgressListener%29

      I hope it works for you too

      Regards

      Delete
  42. Hi, thanks for your example!

    I try to test it but i get the following exception: Uploading file...Exception in thread "main" DropboxServerException (nginx): 403 Forbidden (Forbidden)
    at com.dropbox.client2.RESTUtility.parseAsJSON(RESTUtility.java:263)
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:411)
    at com.dropbox.client2.DropboxAPI$BasicUploadRequest.upload(DropboxAPI.java:1081)
    at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1422)
    at file_upload_dropbox.main(file_upload_dropbox.java:51)

    So my mistake have to be in the line:

    Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, fileContents.length(), null, null);

    I really searched some sites and other examples and i dont know what is wrong ... SDKs documentary says only:

    static int _403_FORBIDDEN
    Usually from an invalid app key pair or other permanent error.

    which is not really useful :(

    Have any idea how i can solve this problem?

    Thanks!

    ReplyDelete
    Replies
    1. Hmm, an odd one. Not come across that I'm afraid so not really sure what's going on - I assume you've double checked your keys are correct?

      Delete
  43. The solution: Access_type of the example and my create app were different :D stupid mistake ... but now it works thanks!

    ReplyDelete
  44. I got the file upload working - it's really great, but what can I do with the keys provided here:
    "AccessTokenPair tokens = session.getAccessTokenPair();
    System.out.println("Use this token pair in future so you don't have to re-authenticate each time:");
    System.out.println("Key token: " + tokens.key);
    System.out.println("Secret token: " + tokens.secret);"

    When I replace my origin keys I got from the DropboxHomepage-App-Information with those Keys provided from the program I always have an error:
    "403 Forbidden (Invalid app key (consumer key). Check your app's configuration to make sure everything is correct.)"

    Could anyone help me please?

    ReplyDelete
    Replies
    1. Hi, I've just added a bit extra detailing what to do with the keys to the post - this works for me (though bear in mind you need to put the keys in exactly!) Does that help?

      Delete
  45. plaese can you help me for how to download a file using dropbox api java
    thank you

    ReplyDelete
  46. i found this code but it's give me null
    import java.io.*;

    import com.dropbox.client2.DropboxAPI;
    import com.dropbox.client2.DropboxAPI.DropboxInputStream;
    import com.dropbox.client2.DropboxAPI.Entry;
    import com.dropbox.client2.exception.DropboxException;
    import com.dropbox.client2.session.AccessTokenPair;
    import com.dropbox.client2.session.AppKeyPair;
    import com.dropbox.client2.session.Session.AccessType;
    import com.dropbox.client2.session.WebAuthSession;

    public class DropboxFile {
    private static final String APP_KEY = "kx2la1hz4lf7hkw"; //Dummy Value.
    private static final String APP_SECRET = "muwp8vczjf8dg5z"; //Dummy Value.

    private static final String TOKEN_KEY = "z1cex8atq5dq62p"; //Dummy Value.
    private static final String TOKEN_SECRET = "wogm6cq640olafr"; //Dummy Value.

    private static final AccessType ACCESS_TYPE = AccessType.DROPBOX;

    private static DropboxAPI api;

    static {
    try {
    AppKeyPair consumerTokenPair = new AppKeyPair(APP_KEY, APP_SECRET);
    AccessTokenPair accessTokenPair = new AccessTokenPair(TOKEN_KEY, TOKEN_SECRET);
    WebAuthSession session = new WebAuthSession(consumerTokenPair, ACCESS_TYPE, accessTokenPair);
    api = new DropboxAPI(session);
    }
    catch (Throwable t) {
    t.printStackTrace();
    }
    }

    //The path to file should be something like : /Documents/Personal/
    //File name should be something like : TopSecret.pdf
    public void downloadFile(String pathToFile, String fileName) {
    FileOutputStream outputStream = null;
    try {
    File file = new File(fileName);
    outputStream = new FileOutputStream(file);
    api.getFile(pathToFile + fileName, null, outputStream, null);
    }
    catch (Exception e) {
    System.out.println(e.getMessage());
    }
    finally {
    if (outputStream != null) {
    try {
    outputStream.close();
    }
    catch (IOException e) {}
    }
    }
    }
    }

    ReplyDelete
  47. If you get a Forbidden error ensure that the ACCESS_TYPE corresponds to how you set up your app - APP_FOLDER or DROPBOX.

    ReplyDelete
    Replies
    1. Thank you so much Christian! Now my app it works!

      Delete
  48. Hi
    do you think is it possilbe in any way to get the direct address link of the uploaded file?
    Tnx a lot
    Francesca

    ReplyDelete
    Replies
    1. Hi Francesca, I've had a quick look at the API but can't see any method for doing this nope - sorry about that! You may have more luck asking on the Dropbox developer forums.

      Delete
  49. Hi there, I'm getting an error with this code...

    Error: WARNING: Authentication error: Unable to respond to any of these challenges: {oauth=WWW-Authenticate: OAuth realm="https://api.dropbox.com/"}

    Can you help me? Thank you.

    ReplyDelete
    Replies
    1. Hi, did you make sure you authenticated your app in the browser (with your dropbox account) before hitting "ok" on the dialog?

      Delete
    2. If I do it like you suggest (WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE, new AccessTokenPair(key, secret));) it gives me that error,

      If I do it without (new AccessTokenPair(key, secret)) i think it runs properly

      Delete
    3. Hmm, are the key and secret definitely exactly the same as the example prints out? Beyond that I'm not really sure, sorry!

      Delete
    4. Now I get another error -.-

      Exception in thread "main" DropboxServerException (nginx): 403 Forbidden (Forbidden)
      at com.dropbox.client2.RESTUtility.parseAsJSON(RESTUtility.java:263)
      at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:411)
      at com.dropbox.client2.DropboxAPI$BasicUploadRequest.upload(DropboxAPI.java:1081)
      at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1422)
      at xptodb.XptoDB.main(XptoDB.java:61)

      Delete
  50. This comment has been removed by the author.

    ReplyDelete
  51. Good post. I have created a web app for generate token:
    apps.camilolopes.com.br/dpboxapiweb the code is here https://github.com/camilolopes/dpboxapiweb

    ReplyDelete
  52. Lila -> You have to authenticate your app Check out this example http://grepcode.com/file/repo1.maven.org/maven2/org.syncloud/dropbox.java.api/1.3.1.1/com/dropbox/client2/DropboxAPI.java

    ReplyDelete
  53. Where do I find the jars libs for these imports:
    import com.dropbox.client2.DropboxAPI;
    import com.dropbox.client2.DropboxAPI.DropboxInputStream;
    import com.dropbox.client2.DropboxAPI.Entry;
    import com.dropbox.client2.exception.DropboxException;
    import com.dropbox.client2.session.AccessTokenPair;
    import com.dropbox.client2.session.AppKeyPair;
    import com.dropbox.client2.session.Session.AccessType;
    import com.dropbox.client2.session.WebAuthSession;

    ReplyDelete
  54. Your blog is very much helpful to me....
    thank you very much :)

    ReplyDelete
  55. where can find those libs you imported in your program

    ReplyDelete
    Replies
    1. You can grab them from here: https://www.dropbox.com/developers/core/sdks/java

      I've updated the post now with this link too.

      Delete
  56. Hey I have to download a file using Public Url (in java),how to achieve that???

    ReplyDelete
  57. Dec 11, 2015 5:12:59 PM org.apache.http.impl.client.DefaultRequestDirector handleResponse
    WARNING: Authentication error: Unable to respond to any of these challenges: {oauth=WWW-Authenticate: OAuth realm="https://api.dropbox.com/"}
    Exception in thread "main" com.dropbox.client2.exception.DropboxUnlinkedException
    at com.dropbox.client2.RESTUtility.parseAsJSON(RESTUtility.java:261)
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:411)
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:337)
    at com.dropbox.client2.RESTUtility.streamRequest(RESTUtility.java:192)
    at com.dropbox.client2.session.WebAuthSession.setUpToken(WebAuthSession.java:218)
    at com.dropbox.client2.session.WebAuthSession.retrieveWebAccessToken(WebAuthSession.java:212)
    at DropBoxApiClass.main(DropBoxApiClass.java:33)
    Dec 11, 2015 5:13:22 PM org.apache.http.impl.conn.IdleConnectionHandler remove
    WARNING: Removing a connection that never existed!




    I am getting this exception u resolve this problem above but i how can i resolve i am not getting so please explain like step wise please

    ReplyDelete
    Replies
    1. Hi, did you make sure you authenticated your app in the browser (with your dropbox account) before hitting "ok" on the dialog?

      Delete
  58. hi i am trying to setup environment on windows platform using java to upload and download files to dropbox . what should i do first to setup environment?

    ReplyDelete
  59. Exception in thread "main" com.dropbox.client2.exception.DropboxIOException: java.net.NoRouteToHostException: No route to host: connect
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:420)
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:337)
    at com.dropbox.client2.RESTUtility.streamRequest(RESTUtility.java:192)
    at com.dropbox.client2.session.WebAuthSession.setUpToken(WebAuthSession.java:218)
    at com.dropbox.client2.session.WebAuthSession.getAuthInfo(WebAuthSession.java:158)
    at com.dropbox.client2.session.WebAuthSession.getAuthInfo(WebAuthSession.java:128)
    at com.javapapers.java.dropbox.JavaDropbox.main(JavaDropbox.java:28)
    Caused by: java.net.NoRouteToHostException: No route to host: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:123)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:133)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
    at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:385)

    ReplyDelete
    Replies
    1. Looks like you have a connectivity issue and can't reach Dropbox - assuming you're connected to the internet, may well be a firewall issue?

      Delete
    2. Actually, it looks like the v1 API is retired which means this example will no longer work. Hold tight, I'll see if I can upload another...

      Delete
    3. See here for a working example: http://berry120.blogspot.co.uk/2017/12/an-updated-dropbox-api-example.html

      Delete
  60. Thanks! Application work since I changed to dropbox-sdk-core 3.5.0, then can log in to the dropbox and got request access code. Unfortunately since I entering access code in GUI shows:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.dropbox.core.DbxRequestUtil.buildUserAgentHeader(DbxRequestUtil.java:151)
    at com.dropbox.core.DbxRequestUtil.addUserAgentHeader(DbxRequestUtil.java:136)
    at com.dropbox.core.DbxRequestUtil.startPostRaw(DbxRequestUtil.java:233)
    at com.dropbox.core.DbxRequestUtil.startPostNoAuth(DbxRequestUtil.java:216)
    at com.dropbox.core.DbxRequestUtil$2.run(DbxRequestUtil.java:453)
    at com.dropbox.core.DbxRequestUtil.runAndRetry(DbxRequestUtil.java:498)
    at com.dropbox.core.DbxRequestUtil.doPostNoAuth(DbxRequestUtil.java:450)
    at com.dropbox.core.DbxWebAuth.finish(DbxWebAuth.java:401)
    at com.dropbox.core.DbxWebAuth.finish(DbxWebAuth.java:383)
    at com.dropbox.core.DbxWebAuth.finishFromCode(DbxWebAuth.java:295)
    at tapp.CloudApp.main(CloudApp.java:43)
    Caused by: java.lang.RuntimeException: Error loading version from resource "sdk-version.txt": Text doesn't follow expected pattern: "${project.version}"
    at com.dropbox.core.DbxSdkVersion.loadVersion(DbxSdkVersion.java:66)
    at com.dropbox.core.DbxSdkVersion.(DbxSdkVersion.java:17)
    ... 11 more

    ReplyDelete

Post a Comment

Popular posts from this blog

The comprehensive (and free) DVD / Blu-ray ripping Guide!

Note: If you've read this guide already (or when you've read it) then going through all of it each time you want to rip something can be a bit of a pain, especially when you just need your memory jogging on one particular section. Because of that, I've put together a quick "cheat sheet" here  which acts as a handy reference just to jog your memory on each key step. I've seen a few guides around on ripping DVDs, but fewer for Blu-rays, and many miss what I believe are important steps (such as ensuring the correct foreign language subtitles are preserved!) While ripping your entire DVD collection would have seemed insane due to storage requirements even a few years ago, these days it can make perfect sense. This guide doesn't show you a one click approach that does all the work for you, it's much more of a manual process. But the benefits of putting a bit more effort in really do pay off - you get to use entirely free tools with no demo versions, it...

Draggable and detachable tabs in JavaFX 2

JavaFX currently doesn't have the built in ability to change the order of tabs by dragging them, neither does it have the ability to detach tabs into separate windows (like a lot of browsers do these days.) There is a general issue for improving TabPanes filed here , so if you'd like to see this sort of behaviour added in the main JavaFX libraries then go ahead and cast your vote, it would be a very welcome addition! However, as nice as this would be in the future, it's not here at the moment and it looks highly unlikely it'll be here for Java 8 either. I've seen a few brief attempts at reordering tabs in JavaFX, but very few examples on dragging them and nothing to do with detaching / reattaching them from the pane. Given this, I've decided to create a reusable class that should hopefully be as easy as possible to integrate into existing applciations - it extends from Tab, and for the most part you create it and use it like a normal tab (you can just add it...