Dropbox Java SDK
repository·main·Indexed 20 days ago
https://github.com/dropbox/dropbox-sdk-javaA Java library for accessing Dropbox's HTTP-based Core API v2, providing a high-level interface for managing files, folders, and user accounts. It supports Java 21+ (v8.0.0+) and Java 8-20 (v7.x), as well as Android 8+ (SDK 26+). The SDK includes features for OAuth2 authentication, global error handling via callback factories, and support for various requestors including OkHttp3.
What's inside dropbox-sdk-java
- The Stone Gradle Plugin is used to automate the generation of Java code from Stone API specifications. This allows developers to maintain type safety and consistency between their API definitions and their Java implementation.
Implement global error handling with callback factories
mainThe Dropbox Java SDK allows you to move away from request-by-request error handling by supplying a callback factory to the client. This enables consistent, global handling of two types of errors:
- General Network Errors: Implement
getNetworkErrorCallbackto handle errors that occur at the networking layer, such as authentication errors. - Route-Specific Errors: Implement one of the
getRouteErrorCallbackmethods to handle errors specific to certain API endpoints or routes.
This pattern is useful for centralizing error logic (like logging or re-authentication flows) that should apply to all requests regardless of the specific endpoint being called.
- General Network Errors: Implement
Setup the Dropbox SDK for Android
mainTo use the Dropbox SDK in an Android project, add the core and Android-specific dependencies to your
build.gradlefile.Note on Kotlin: The Android SDK is written in Kotlin. If your project does not already include Kotlin, you must add the Kotlin standard library as a dependency to avoid runtime exceptions.
Jettifier Workaround: If you encounter transformation errors with
jackson-coreorfastdoubleparserwhile using Jettifier, add the following to yourgradle.properties:android.jetifier.ignorelist = jackson-core,fastdoubleparserdependencies { // ... implementation 'com.dropbox.core:dropbox-core-sdk:8.0.2' implementation 'com.dropbox.core:dropbox-android-sdk:8.0.2' // Required if your project doesn't have Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib:2.4.0" }Run the Dropbox Java SDK Tutorial Example
mainThe tutorial example demonstrates basic usage of the Dropbox Java SDK. To run the provided example code, you must provide a valid Dropbox access token.
- Locate
Main.javain the example source. - Replace the placeholder
"<ACCESS TOKEN>"with your actual Dropbox access token. - Refer to the official Dropbox online tutorial for instructions on how to generate an access token and complete the setup.
// In Main.java, replace the placeholder with your token: String accessToken = "<ACCESS TOKEN>";- Locate
Use the published Dropbox SDK in an Android project
mainThe provided Android example uses the local source version of the SDK. To use the published version of the SDK in your own Android project instead of the local source, modify your
build.gradlefile to replace the project dependency with the remote Maven dependency.Replace:
implementation(project(":core"))With:
implementation("com.dropbox.core:dropbox-core-sdk:LATEST_VERSION_GOES_HERE")// Replace this: implementation(project(":core")) // With this: implementation("com.dropbox.core:dropbox-core-sdk:LATEST_VERSION_GOES_HERE")Initialize a Dropbox client
mainTo interact with the Dropbox API, you must instantiate a
DbxClientV2. This requires aDbxRequestConfig(which includes a client name for identification) and an access token obtained from the Dropbox App Console.import com.dropbox.core.DbxException; import com.dropbox.core.DbxRequestConfig; import com.dropbox.core.v2.DbxClientV2; public class Main { private static final String ACCESS_TOKEN = "<ACCESS TOKEN>"; public static void main(String args[]) throws DbxException { // Create Dropbox client DbxRequestConfig config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build(); DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN); } }Install the Dropbox Java SDK
mainYou can add the Dropbox Java SDK to your project using Maven or Gradle.
Note on Java Versions:
- v8.0.0+: Requires Java 21+.
- v7.x: Supports Java 8 through Java 20.
Note on Android:
- Supports Android 8+ (SDK 26+).
### Maven ```xml <dependency> <groupId>com.dropbox.core</groupId> <artifactId>dropbox-core-sdk</artifactId> <version>8.0.2</version> </dependency>Gradle
dependencies { // ... implementation 'com.dropbox.core:dropbox-core-sdk:8.0.2' }Build and run Dropbox SDK examples from source
mainTo run the provided examples in the repository, follow these steps:
- Build the SDK:
git clone https://github.com/dropbox/dropbox-sdk-java.git cd dropbox-sdk-java ./update-submodules ./gradlew build - Configure Credentials: Create a JSON file (e.g.,
test.app) containing yourkeyandsecretfrom the Dropbox App Console. - Run Examples: Use the
./runscript in theexamplesdirectory.
Common Example Commands:
- OAuth Authorization:
./run authorize test.app test.auth(generatestest.authcontaining the access token). - Account Info:
./run account-info test.auth. - Longpoll (Watch changes):
./run longpoll test.auth "/path/to/watch". - Upload File:
./run upload-file test.auth local-path/file.txt /dropbox-path/file.txt.
# Build from source ```shell git clone https://github.com/dropbox/dropbox-sdk-java.git cd dropbox-sdk-java ./update-submodules # also do this after every "git checkout" ./gradlew build # requires `python` command to use Python 3.9, pip dropboxRunning the examples
cd examples ./run authorize test.app test.auth ./run account-info test.auth ./run longpoll test.auth "/path/to/watch" ./run upload-file test.auth local-path/file.txt /dropbox-path/file.txt
- Build the SDK:
Implement certificate pinning
mainAs of version 7.0.0, the SDK no longer provides certificate pinning by default and
SSLConfigis no longer available. You must provide your ownSSLSocketFactoryorCertificatePinnerusing the available requestors.// Using StandardHttpRequestor StandardHttpRequestor.Config customConfig = StandardHttpRequestor.Config.DEFAULT_INSTANCE.copy() .withSslSocketFactory(mySslSocketFactory) .build(); StandardHttpRequestor requestor = new StandardHttpRequestor(customConfig); // Using OkHttp3Requestor okhttp3.OkHttpClient httpClient = OkHttp3Requestor.defaultOkHttpClientBuilder() .certificatePinner(myCertificatePinner) .build(); // Using OkHttpRequestor OkHttpClient httpClient = OkHttpRequestor.defaultOkHttpClient().clone() .setCertificatePinner(myCertificatePinner) .build();Set up the Dropbox Android Example project
mainTo run the Android example application, you must provide your Dropbox App/API Key. This is done by creating a
local.propertiesfile within the Android example directory (examples/android/local.properties).Note: Creating this file is not required to build the app, but it is mandatory if you want to test the authentication flow.
Steps:
- Ensure your build environment supports at least Android SDK version 21 (Android 5.0 Lollipop).
- Create
examples/android/local.propertieswith the following content:DROPBOX_APP_KEY=YOUR_KEY_HERE(replaceYOUR_KEY_HEREwith your actual Dropbox App/API Key).
You can automate this via the terminal from the root of the
dropbox-sdk-javarepository:echo "DROPBOX_APP_KEY=YOUR_KEY_HERE" > examples/android/local.propertiesConfigure AndroidManifest.xml for Dropbox Authentication
mainTo enable Dropbox authentication on Android, you must configure your
AndroidManifest.xmlwith two specific components:AuthActivity: Register the
com.dropbox.core.android.AuthActivitywith anintent-filterusing your specific Dropbox App Key in the scheme (db-${dropboxKey}).- The activity starting the authorization flow must have
android:launchMode="singleTask". - If your activity uses
android:taskAffinity, ensureAuthActivityuses the same affinity. - A second
intent-filteris included as a workaround for apps targetingtargetSdk=33.
- The activity starting the authorization flow must have
Queries: Add the Dropbox package name to your
<queries>block to allow the SDK to verify the official Dropbox app during the app-to-app authentication flow.
<manifest> ... <application> <activity android:name="com.dropbox.core.android.AuthActivity" android:exported="true" android:configChanges="orientation|keyboard" android:launchMode="singleTask"> <intent-filter> <data android:scheme="db-${dropboxKey}" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <!-- Workaround for targetSdk=33 --> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> <queries> <package android:name="com.dropbox.android" /> </queries> ... </manifest>Configure the Stone Gradle Plugin
mainThe Stone Gradle Plugin automates the generation of Stone Java source files. When applied, it automatically creates generation tasks for every available
SourceSetin your project and ensures thatJavaCompileandKotlinCompiletasks depend on these generation tasks so that code is generated before compilation begins.Generated Tasks
For each source set, a task is registered with the following naming convention:
mainsource set:generateStone- Other source sets (e.g.,
test):generateTestStone
Configuration Properties
You can configure the plugin via Gradle project properties using the following naming patterns:
Property Name Description com.dropbox.api.${sourceSet.name}.routeWhitelistFilterPath to a file containing the route whitelist filter. com.dropbox.api.${sourceSet.name}.specDirThe directory containing Stone specifications. Defaults to src/${sourceSet.name}/stone.Default Behavior
- Generator File: Uses
${projectDirectory}/generator/java/java.stoneg.py. - Stone Directory: Defaults to
stone. - Python Command: Defaults to
python. - Output Directory: Generated files are placed in
build/generated/source/stone/${sourceSet.name}/srcand are automatically added to the corresponding source set's Java source directories.