Article : Quickstart: Run a Drive App in Java

Quickstart: Run a Drive App in Java


Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Drive app that uploads a file to Google Drive. If you like, you can view a video of Google engineers guiding you through the steps.

1.Step 1: Enable the Drive API
2.Step 2: Install the Google Client Library
3.Step 3: Set up the sample
4.Step 4: Run the sample
5.Optional: View a quickstart video
To run a quickstart example you'll need:

•Access to the internet and a web browser, in order to authorize the sample app.
•A Google account with Drive enabled.
•An environment to run programs in your selected language.
Step 1: Enable the Drive API
If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

1.Go to the Google Developers Console. 


2.Select a project.
3.In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Drive API.
4.In the sidebar on the left, select Credentials.
In either case, you end up on the application's credentials page.

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

Take note of the Client ID as you'll need to add it to your code later.

Step 2: Install the Google Client Library
To install the Google API Java Client, you must download two ZIP files, extract them, and then copy the JARs into your Java classpath.


1.Download the Google Drive Java client library, which is bundled as a ZIP file with all the required dependencies.
2.Extract the ZIP file
3.Add all of the JARs within the libs directory to your classpath.
4.Add the google-api-services-drive-v2-[version].jar jar to your classpath.

If you are using Eclipse, see here for instructions on adding JARs to your project's classpath.

If you are using NetBeans, see here for instructions on adding JARs to your project's classpath.

If you are using IntelliJ IDEA, see here for instructions on adding JARs to your project's classpath.

If developing from the command line, add -classpath /path/to/directory/with/unzipped/jars to your javac and java command invocations.

Step 3: Set up the sample
You'll need to create two files: a test file to upload to Drive (in this case document.txt), and the given sample code, modified to include the unique Client ID and Client Secret you created in the "Enable the Drive API" step.

1.Create a text file named document.txt, containing the text Hello world!. The file must be in the same location as the source code you paste from below. If you are using Java with an IDE, it is important that document.txt be in your project.
2.After following the directions below to copy source code, replace YOUR_CLIENT_ID with the Client ID you generated in the "Enable the Drive API" step.
3.Replace YOUR_CLIENT_SECRET with your Client Secret, also generated previously.
Copy the following source code to DriveCommandLine.java. If using an IDE, such as Eclipse, Netbeans, or IntelliJ IDEA, make sure to setup a project first before creating the file.


import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;import com.google.api.client.http.FileContent;import com.google.api.client.http.HttpTransport;import com.google.api.client.http.javanet.NetHttpTransport;import com.google.api.client.json.JsonFactory;import com.google.api.client.json.jackson2.JacksonFactory;import com.google.api.services.drive.Drive;import com.google.api.services.drive.DriveScopes;import com.google.api.services.drive.model.File;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;public class DriveCommandLine {  private static String CLIENT_ID = "YOUR_CLIENT_ID";  private static String CLIENT_SECRET = "YOUR_CLIENT_SECRET";  private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";  public static void main(String[] args) throws IOException {  HttpTransport httpTransport = new NetHttpTransport();  JsonFactory jsonFactory = new JacksonFactory();  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(  httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))  .setAccessType("online")  .setApprovalPrompt("auto").build();  String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();  System.out.println("Please open the following URL in your browser then type the authorization code:");  System.out.println("  " + url);  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  String code = br.readLine();  GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();  GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);  //Create a new authorized API client  Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();  //Insert a file  File body = new File();  body.setTitle("My document");  body.setDescription("A test document");  body.setMimeType("text/plain");  java.io.File fileContent = new java.io.File("document.txt");  FileContent mediaContent = new FileContent("text/plain", fileContent);  File file = service.files().insert(body, mediaContent).execute();  System.out.println("File ID: " + file.getId());  }}
Step 4: Run the sample
After you have set up your Google API project, installed the Google API client library, and set up the sample source code, the sample is ready to run. When you run the sample from command-line, it provides a link you'll need to visit in order to authorize.

If you're using an IDE, make sure you have a default run target set that targets the DriveCommandLine class. However, the following steps are for running the sample from the command line.

1.Compile the sample using:

javac -classpath /path/to/google/lib/*:/path/to/google/lib/libs/* DriveCommandLine.java`2.Run the sample using:

java -classpath ./:/path/to/google/lib/*:/path/to/google/lib/libs/* DriveCommandLine3.Browse to the provided URL in your web browser.

4.If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
5.Copy the code you're given after browsing to the link, and paste it into the prompt Enter authorization code:. Click Enter.
Note: The authorization flow in this example is greatly simplified for demonstration purposes and should not be used in web applications. For more information, see Authorizing your App with Google Drive.
When you finish these steps, the sample prints information about the Google Drive file to the screen. The file document.txt is accessible in Google Drive, and is titled "My Document".

By editing the sample code to provide paths to new files and new titles, you can run a few more simple upload tests. When you're ready, you could try running some other Drive API methods such as files.list.

Optional: View a quickstart video
Videos that cover the setup and running of each quickstart sample in detail. If you'd like to see the Java quickstart sample demonstrated by some of the same developers who wrote it, click play, sit back, and enjoy.


Next Steps
If your goal is to let users create and open files directly from the Drive UI using your app, see Integrate with the Drive UI. Our end-to-end Example Apps demonstrate a simple Drive UI-integrated web app.

If your goal is to expand the quickstart sample into something for your own installed application, consult the API Reference. The API Reference discusses all of the features of the Drive API, and gives samples in each language on how to use a feature.

All requests to the Drive API must be authorized by an authenticated user. To examine more authorization code and learn how to authorize requests, see Authorizing Your App with Google Drives.