cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
Share your feedback on the Document Scanning Experience in the Dropbox App right here.

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How can i get lifetime Access Token

How can i get lifetime Access Token

Ghost Mjrm
Explorer | Level 4

i have android app connected to my Dropbox folder using access token but every 4 hour should i edit my code and input the new access token is there any method to make the app working 24h without any interact from me

and fix the message that show access token error uploading to Dropbox: expired access token

 

 

private void uploadToDropbox(File photoFile) {
if (photoFile == null || !photoFile.exists()) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: Photo file does not exist", Toast.LENGTH_SHORT).show());
return;
}

DbxRequestConfig config = DbxRequestConfig.newBuilder("Decamera").build();
DbxClientV2 client = new DbxClientV2(config, DROPBOX_ACCESS_TOKEN);

try {
String remotePath = "/Decamera/" + photoFile.getName();

try (InputStream in = new FileInputStream(photoFile)) {
client.files().uploadBuilder(remotePath)
.withMode(WriteMode.ADD)
.uploadAndFinish(in);

runOnUiThread(() -> Toast.makeText(MainActivity.this, "Photo uploaded to Dropbox", Toast.LENGTH_SHORT).show());
}

} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error uploading to Dropbox: " + e.getMessage(), Toast.LENGTH_SHORT).show());
}
}
private static final String DROPBOX_ACCESS_TOKEN = my access token

 

1 Accepted Solution

Accepted Solutions

Здравко
Legendary | Level 20

@Ghost Mjrm, Be more careful when inspecting the code.

 


@Ghost Mjrm wrote:
... there is no offline ...

Hm..:thinking_face: Let's see where the OAuth starts here and what actually gets executed here. 🧐 Are you still thinking "there is no offline"? :slightly_smiling_face:

 


@Ghost Mjrm wrote:
... or refresh token example

Let's see where OAuth finish here and what actually it executes here. Ahhh... where was this refresh token... :winking_face:

Keep more attention on code reading.

View solution in original post

41 Replies 41

Здравко
Legendary | Level 20

@Ghost Mjrm, There is no way to get non expiring access token. As discussed before, you need to use refresh token instead. Refresh token doesn't expire automatic, so you can use it more than 24 hours. :winking_face: Use OAuth as Greg suggested there. Don't forget to set offline access.

Good luck.

Ghost Mjrm
Explorer | Level 4
Can you help me with that how can i edit my code to achieve that i‘m beginner and I don’t have that experience to do that so if you can give me the instructions step by step 🫡:rose:

Здравко
Legendary | Level 20

You can take a look on the example here.

Ghost Mjrm
Explorer | Level 4
Do you have more resources I didn’t find this useful idk why but there is no offline or refresh token example

Здравко
Legendary | Level 20

@Ghost Mjrm, Be more careful when inspecting the code.

 


@Ghost Mjrm wrote:
... there is no offline ...

Hm..:thinking_face: Let's see where the OAuth starts here and what actually gets executed here. 🧐 Are you still thinking "there is no offline"? :slightly_smiling_face:

 


@Ghost Mjrm wrote:
... or refresh token example

Let's see where OAuth finish here and what actually it executes here. Ahhh... where was this refresh token... :winking_face:

Keep more attention on code reading.

Ghost Mjrm
Explorer | Level 4

aha yeah i don't know how you got there but its seem to me he is using kotlin not java but i will figure it out

thanks (:

Здравко
Legendary | Level 20

@Ghost Mjrm wrote:

aha yeah i don't know how you got there ...


It's the internals of same link, I posted before. Nothing new.

 


@Ghost Mjrm wrote:

... but its seem to me he is using kotlin not java but i will figure it out

...


Kotlin is widely used as a Java replacement (it's definitely more powerful), so Dropbox does the same. Both of them are using the same JVM, so they are compatible and you can use Java while Dropbox Java SDK for Android is in fact not Java but Kotlin. Again, Kotlin and Java languages can be mixed troubleless (there are some small exceptions only, that don't affect you in the particular case).

Good luck. :winking_face:

Ghost Mjrm
Explorer | Level 4

i have done with the code but im facing a problem with the redirected uri

in my situation and in my code i want the user after make oauth flow and done with it and get the access token then my app use this token to upload photo

i dont want the user to redirect to http site or somthing so now i got this error after setting the redirect uri to redirect user to my app

error 400 invalid redirect_uri. when response_type=code without PKCE,redirect_uri must start with "https://", unless its a localhost URI

Ghost Mjrm
Explorer | Level 4
this is my app code now look like
private static final
String DROPBOX_APP_KEY = "secret";
private static final String DROPBOX_APP_SECRET = "secret";
private static final String DROPBOX_REDIRECT_URI = "decamera://auth-finish";

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

previewView = findViewById(R.id.previewView);
ImageButton captureButton = findViewById(R.id.captureButton);
ImageButton leftCornerButton = findViewById(R.id.leftCornerButton);
addressTextView = findViewById(R.id.addressTextView);

fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
geocoder = new Geocoder(this, Locale.getDefault());

captureButton.setOnClickListener(this);

leftCornerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initiateDropboxAuthorization();
}
});

addressTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditAddressDialog();
}
});

if (allPermissionsGranted()) {
startCamera();
getLastLocation();
} else {
ActivityCompat.requestPermissions(this, REQUIRED_CAMERA_PERMISSIONS, CAMERA_PERMISSION_REQUEST);
}

// Initialize Dropbox access token if available
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
DROPBOX_ACCESS_TOKEN = prefs.getString("dropboxAccessToken", null);

// Check if the app was opened with a Dropbox authorization callback
handleDropboxAuthorizationCallback(getIntent());
}

// Override onNewIntent to handle the Dropbox authorization callback
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleDropboxAuthorizationCallback(intent);
}

private void handleDropboxAuthorizationCallback(Intent intent) {
Uri data = intent.getData();
if (data != null && data.toString().startsWith(DROPBOX_REDIRECT_URI)) {
// Authorization successful, extract the authorization code
String code = data.getQueryParameter("code");

// Now, exchange the authorization code for an access token and refresh token
exchangeAuthorizationCodeForTokens(code);
}
}

private void initiateDropboxAuthorization() {
// Construct the Dropbox authorization URL
String authorizationUrl = "https://www.dropbox.com/oauth2/authorize" +
"?client_id=" + DROPBOX_APP_KEY +
"&response_type=code" +
"&token_access_type=offline" +
"&state=myState" + // Replace with your own state
"&redirect_uri=" + DROPBOX_REDIRECT_URI;

// Open the authorization URL in a web browser or WebView
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authorizationUrl));
startActivity(browserIntent);
}
private String performPostRequest(String requestUrl, String urlParameters) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
connection.setDoOutput(true);

// Write the request body
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}

// Get the response
try (InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
return response.toString();
}
} catch (Exception e) {
Log.e("HTTP", "Error in HTTP request: " + e.getMessage());
return null;
}
}
private void exchangeAuthorizationCodeForTokens(String code) {
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String url = "https://api.dropbox.com/oauth2/token";
String requestBody = "code=" + params[0] +
"&grant_type=authorization_code" +
"&client_id=" + DROPBOX_APP_KEY +
"&client_secret=" + DROPBOX_APP_SECRET +
"&redirect_uri=" + DROPBOX_REDIRECT_URI;

// Perform the POST request and obtain the JSON response
String jsonResponse = performPostRequest(url, requestBody);

// Parse the JSON response to extract access and refresh tokens
JSONObject jsonObject = new JSONObject(jsonResponse);
DROPBOX_ACCESS_TOKEN = jsonObject.getString("access_token");

// Save the Dropbox access token
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
prefs.edit().putString("dropboxAccessToken", DROPBOX_ACCESS_TOKEN).apply();

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(code);
}


private void uploadToDropbox(File photoFile) {
if (photoFile == null || !photoFile.exists()) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: Photo file does not exist", Toast.LENGTH_SHORT).show());
return;
}

if (DROPBOX_ACCESS_TOKEN == null) {
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: Dropbox access token is null", Toast.LENGTH_SHORT).show());
return;
}

DbxRequestConfig config = DbxRequestConfig.newBuilder("Decamera").build();
DbxClientV2 client = new DbxClientV2(config, DROPBOX_ACCESS_TOKEN);

try {
String remotePath = "/Decamera/" + photoFile.getName();

try (InputStream in = new FileInputStream(photoFile)) {
client.files().uploadBuilder(remotePath)
.withMode(WriteMode.ADD)
.uploadAndFinish(in);

runOnUiThread(() -> Toast.makeText(MainActivity.this, "Photo uploaded to Dropbox", Toast.LENGTH_SHORT).show());
}

} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error uploading to Dropbox: " + e.getMessage(), Toast.LENGTH_SHORT).show());
}
Need more support?
Who's talking

Top contributors to this post

  • User avatar
    Ghost Mjrm Explorer | Level 4
  • User avatar
    Здравко Legendary | Level 20
What do Dropbox user levels mean?