Search This Blog

Thursday, 16 February 2012

Dropbox Java 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.)

110 comments:

  1. Replies
    1. 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 ?

      Delete
    2. 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.

      Delete
    3. 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 !!!!

      Delete
    4. 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.

      Delete
    5. 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 = "********";

      Delete
    6. 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.

      Delete
    7. ok I'll do this
      thank you

      Delete
    8. 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

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

      Delete
    10. 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 ?

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

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

      Delete
    13. In exactly the same way - simply swap the file name over!

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

      Delete
    15. 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);

      Delete
    16. 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.

      Delete
    17. 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 ?

      Delete
    18. 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.

      Delete
    19. 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

      Delete
    20. 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);

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

      Delete
    22. 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

      Delete
  2. 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
  3. Replies
    1. No problem, glad you found it useful!

      Delete
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. This comment has been removed by the author.

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

      Delete
  12. 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
  13. Replies
    1. No problem, glad it's useful to you!

      Delete
  14. 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
  15. 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
  16. 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
  17. Thanks! This tut saved a lot of my time. You rock!

    ReplyDelete
  18. 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
  19. 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
  20. i nee urgent reply and can u explain form of steps

    ReplyDelete
  21. 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
  22. 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
  23. 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
  24. 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
  25. The solution: Access_type of the example and my create app were different :D stupid mistake ... but now it works thanks!

    ReplyDelete
    Replies
    1. Ah, no worries - glad it's now sorted!

      Delete
  26. 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
  27. plaese can you help me for how to download a file using dropbox api java
    thank you

    ReplyDelete
  28. 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
  29. 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
  30. 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
  31. 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
  32. This comment has been removed by the author.

    ReplyDelete
  33. 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
  34. 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
  35. Your blog is very much helpful to me....
    thank you very much :)

    ReplyDelete
  36. 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
  37. Hey I have to download a file using Public Url (in java),how to achieve that???

    ReplyDelete
  38. 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
    2. Token PAir : {key="UVKnRR2wrIudYUtu", secret="NVRuioOZVz7p8u24"}
      Authentication Successful!
      {key="UVKnRR2wrIudYUtu", secret="NVRuioOZVz7p8u24"} : AccessToken 2
      com.dropbox.core.DbxClient@b7f23d9
      Dec 15, 2015 4:44:38 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/"}
      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.RESTUtility.request(RESTUtility.java:122)
      at com.dropbox.client2.DropboxAPI.createFolder(DropboxAPI.java:1917)
      at NewDropBoxWebAuthTest.createFolder(NewDropBoxWebAuthTest.java:47)
      at NewDropBoxWebAuthTest.main(NewDropBoxWebAuthTest.java:81)


      Sorry for late reply this is my out put i am authenticated successfully but this exception i am getting if any modifications i done in my project

      Delete
  39. 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