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.
/**
* 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.)
Thank you!
ReplyDeleteYou're welcome!
Deletei have some problems in this program ,
Deletein 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.
Deletewhen this program run i have this message :
DeleteException 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.
Deletei already have a count in dropbox
Deletemy 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.)
DeleteWhen 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
Deletethank 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
DeleteWhat do you mean by "doesn't run"? What error / exception do you get specifically?
Deletei haven't error but i don't upload the file testing.txt in the end of the run i have :
DeleteUploading 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!
Deleteok, i have a file.pdf i want to upload this in dropbox , how to do ?
DeleteIn exactly the same way - simply swap the file name over!
Deleteplease could you help me, i want to upload a file.pdf in dropbox , how does to process
Deletethank'you
i do like this, but it's not correct :
DeleteSystem.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.
Deleteok, thank'you but how to do ?
Deletei 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"));
DeleteThis 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
Deletelike this but it doesn't run : System.out.print("Uploading file...");
DeleteString 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
Deletethank'you
Uploading 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.
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?
DeleteAmazing!
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.
DeleteThis comment has been removed by the author.
ReplyDeleteThank 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!
Deletegreat 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.
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, 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.
ReplyDelete