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.)
To use the token pair in future, instead of doing:
You would do:
...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.)
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.)
You're welcome!
ReplyDeleteUploading file...DbExample LogUser has unlinked
ReplyDeletehow can i solve it?
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
DeleteThank you.it is useful!!
ReplyDeleteNo problem, glad you found it useful!
Deleteit shows error at line 29..
ReplyDeleteAh, 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.)
DeleteTo fix it, simply explicitly put WebAuthSession between < and >:
mDBApi = new DropboxAPI<WebAuthSession>(session);
Then it should all be fine.
I am getting the following error, can you help?
ReplyDeleteErrors:
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);
}
}
Thanks for the sample code. I tried using it but I got the following error at
ReplyDeleteWebAuthInfo 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.
I have also the same error in Ubuntu , but in Mac OS is not happening, any idea ?
DeleteNot sure I'm afraid - haven't encountered this one myself. Perhaps check in case it's a firewall issue?
DeleteAre you using OpenJDK on OSX?
DeleteFigured 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
Amazing!
ReplyDeleteBut...
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
You need the Apache Commons library on your classpath, it looks like you haven't got it here.
DeleteAwesome it helped me much. :)
DeleteI 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?
It's probably because your unit tests are using the Dropbox functionality in some way.
DeleteYou 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!)
I receive an error in line: session.retrieveWebAccessToken(pair);
ReplyDelete"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?
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.
DeleteSkipping the lines will never work, since without that authentication the program won't have the authentication to write or read to any files.
thanks for reply!I resolved this.
DeleteI 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?
I believe it is forever, since you're authenticating the application with your dropbox account and that's not something I think expires.
DeleteException in thread "main" com.dropbox.client2.exception.DropboxUnlinkedException
ReplyDeleteat 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
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.
DeleteThank U Very Much....
ReplyDeleteYou're welcome, glad it has proved useful to so many people!
DeleteHates off to you Berry...
ReplyDeleteThanks 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...
Glad you found it helpful!
DeleteThank your very match!
ReplyDeleteNo problem, glad it's useful to you!
DeleteHi berry,
ReplyDeleteExcellent 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 :)
Thanks for the comments!
DeleteOn 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.)
See below for the simple explanation of how to reuse the token :-)
DeleteI could not figure out, how to reuse the access token pair the next time around. Could you post a snippet for that?
ReplyDeleteHey - it should be as easy as using the 3 parameter constructor of WebAuthSession, so instead of:
DeleteWebAuthSession 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!
Hey, great article. But I had a doubt. Is there any way I can upload folders the same way?
ReplyDeleteHi Om,
DeleteYou 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.)
Thanks! This tut saved a lot of my time. You rock!
ReplyDeleteGlad it proved useful!
Deletei have some problems in this program ,
ReplyDeletein APP_KEY = "APP KEY"
APP_SECRET = "SECRET KEY"
what do I have to in APP_KEY and APP_SECRET ?
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.
ReplyDeletewhen this program run i have this message :
ReplyDeleteException 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 !!!!
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.
ReplyDeletei already have a count in dropbox
ReplyDeletemy user name is : lilahassena@gmail.com end the password
is what I have to do like this:
APP_KEY = "lilahassena@gmail.com";
APP_SECRET = "********";
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.)
ReplyDeleteWhen 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.
ok I'll do this
ReplyDeletethank you
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
ReplyDeleteWhat do you mean by "doesn't run"? What error / exception do you get specifically?
ReplyDeletei haven't error but i don't upload the file testing.txt in the end of the run i have :
ReplyDeleteUploading file...Done.
Revision of file: 20db990cd
how to do for upload the file ?
If you see that output, then it's definitely uploaded the file and given you a revision number. All is well, no problems!
ReplyDeleteok, i have a file.pdf i want to upload this in dropbox , how to do ?
ReplyDeleteIn exactly the same way - simply swap the file name over!
ReplyDeletegreat 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?
ReplyDeleteDesktop.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.
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.
DeleteIt 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.
please could you help me, i want to upload a file.pdf in dropbox , how does to process
ReplyDeletethank'you
i do like this, but it's not correct :
ReplyDeleteSystem.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);
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.
ReplyDeleteok, thank'you but how to do ?
ReplyDeletei don't know how to do for upload a PDF file ,
how to do for pass a FileInputStream ?
You construct a file input stream like so: FileInputStream fis = new FileInputStream(new File("myFile.pdf"));
ReplyDeleteThis 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.
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
ReplyDeletelike this but it doesn't run : System.out.print("Uploading file...");
ReplyDeleteString 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);
hello, could you help me for how to download file in dropbox-api using java
ReplyDeletethank'you
Exception in thread "main" com.dropbox.client2.exception.DropboxUnlinkedException
ReplyDeleteat 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
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!
Deletei nee urgent reply and can u explain form of steps
ReplyDeleteplease can you help for how to download file in dropbox using java
ReplyDeletei found how to upload but not how to download
thank'you
i found this but doesn't fonction
ReplyDeleteFileOutputStream 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
Hi Lila,
DeleteWhat 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!)
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
Deletethank you for your answer is kind of you
Hi Lila,
DeleteYou 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.
I found something in the web
Deletehe 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"
it doesn't any exception the code run normally ,
DeleteI 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
This comment has been removed by the author.
DeleteSo 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.
Deleteyou don't understand is that I want!
DeleteI want to upload a fle from a dropbox
you known any method (code) to do this
thank you
please have you any idea for :
Deletehow to download file in dropbox using java
please I'm really lost, if someone has a method to how download file using dropbox api with java
Deletehe told me,
please
thank's
why nobody wants to help me,
ReplyDeletethis is really urgent
Please if anyone has an idea to help me
"" how to download file in dropbox using java ""
thank you
Hi lila!
DeleteThis 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
Hi, thanks for your example!
ReplyDeleteI 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!
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?
DeleteThe solution: Access_type of the example and my create app were different :D stupid mistake ... but now it works thanks!
ReplyDeleteAh, no worries - glad it's now sorted!
DeleteI got the file upload working - it's really great, but what can I do with the keys provided here:
ReplyDelete"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?
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?
Deleteplaese can you help me for how to download a file using dropbox api java
ReplyDeletethank you
i found this code but it's give me null
ReplyDeleteimport 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) {}
}
}
}
}
If you get a Forbidden error ensure that the ACCESS_TYPE corresponds to how you set up your app - APP_FOLDER or DROPBOX.
ReplyDeleteThank you so much Christian! Now my app it works!
DeleteHi
ReplyDeletedo you think is it possilbe in any way to get the direct address link of the uploaded file?
Tnx a lot
Francesca
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.
DeleteThanks anyway :)
DeleteHi there, I'm getting an error with this code...
ReplyDeleteError: 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.
Hi, did you make sure you authenticated your app in the browser (with your dropbox account) before hitting "ok" on the dialog?
DeleteIf I do it like you suggest (WebAuthSession session = new WebAuthSession(appKeys, ACCESS_TYPE, new AccessTokenPair(key, secret));) it gives me that error,
DeleteIf I do it without (new AccessTokenPair(key, secret)) i think it runs properly
Hmm, are the key and secret definitely exactly the same as the example prints out? Beyond that I'm not really sure, sorry!
DeleteNow I get another error -.-
DeleteException 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)
This comment has been removed by the author.
ReplyDeleteGood post. I have created a web app for generate token:
ReplyDeleteapps.camilolopes.com.br/dpboxapiweb the code is here https://github.com/camilolopes/dpboxapiweb
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
ReplyDeleteWhere do I find the jars libs for these imports:
ReplyDeleteimport 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;
never mind.. I got it..
ReplyDeleteYour blog is very much helpful to me....
ReplyDeletethank you very much :)
where can find those libs you imported in your program
ReplyDeleteYou can grab them from here: https://www.dropbox.com/developers/core/sdks/java
DeleteI've updated the post now with this link too.
Hey I have to download a file using Public Url (in java),how to achieve that???
ReplyDeleteDec 11, 2015 5:12:59 PM org.apache.http.impl.client.DefaultRequestDirector handleResponse
ReplyDeleteWARNING: 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
Hi, did you make sure you authenticated your app in the browser (with your dropbox account) before hitting "ok" on the dialog?
Deletehi 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?
ReplyDeleteException in thread "main" com.dropbox.client2.exception.DropboxIOException: java.net.NoRouteToHostException: No route to host: connect
ReplyDeleteat 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)
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?
DeleteActually, 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...
DeleteSee here for a working example: http://berry120.blogspot.co.uk/2017/12/an-updated-dropbox-api-example.html
DeleteThanks! 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:
ReplyDeleteException 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