我正在使用Google Sheets API来获取Java项目的图纸数据。所有这些都在本地正常工作,但是我使用了详细的权限范围https://www.googleapis.com/auth/spreadsheets,该范围“允许对用户工作表及其属性进行读/写访问。”。我不希望不向该应用程序提供对我的Google云端硬盘中所有电子表格的访问权限(只是暂时在本地进行)。
理想情况下,我想请求使用文件ID对文件进行读/写访问的权限。这可能吗?
如果无法实现,我猜想是https://www.googleapis.com/auth/drive.file范围提供了“对应用程序创建或打开的文件的按文件访问”。是我能得到的最接近的。我尚未设法找到一种使用此应用打开文件的方法。我将如何去做?
或者如果上述两种解决方案都不理想或不可能,请告诉我您的建议。
谢谢!
答案 0 :(得分:4)
我知道这是很久以前发布的,但是我会给出答案,以帮助将来的开发人员遇到这种情况。
我认为使用服务帐户可以为您提供在此寻找的功能。服务帐户有点像“ bot”用户,用户可以与他们共享文档,然后您的服务器可以登录到该服务帐户以访问那些文档。不必要求访问用户的整个Google驱动器或Google表格,您可以让他们手动与您共享文档,对于大多数用户而言,我认为这样比较舒适。
Here is an example,了解如何在Node.js中进行设置,但是这些想法应该可以很容易地转化为Java。
答案 1 :(得分:0)
作用域授予您对api的访问权限,无法将其限制为单个文件或文件组。
Google Sheets API,第4版范围
无法将权限限制为单个文件。假设您正在编辑的文件是由应用程序创建的,那么https://www.googleapis.com/auth/drive.file
应该是有效的选项
样品
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
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.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.ValueRange;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class SheetsQuickstart {
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receier = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receier).authorize("user");
}
/**
* Prints the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
final String range = "Class Data!A2:E";
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.isEmpty()) {
System.out.println("No data found.");
} else {
System.out.println("Name, Major");
for (List row : values) {
// Print columns A and E, which correspond to indices 0 and 4.
System.out.printf("%s, %s\n", row.get(0), row.get(4));
}
}
}
}
答案 2 :(得分:0)
我认为,这就是您所要求的。 (https://developers.google.com/sheets/api/quickstart/java,https://www.youtube.com/watch?v=zDxTSUWaZs4) 我正在使用此代码通过ID访问Google工作表
public class ConnectToDatabase extends AsyncTask<Object, Integer, Long> {
private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
private static String SPREADSHEET_ID = INSERTYOURIDHERE;
private static MainActivity main_Activity = null;
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);
private static final String CREDENTIALS_FILE_PATH = "credentials.json";
public ConnectToDatabase(MainActivity mainActivity) {
this.main_Activity = mainActivity;
}
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in =
main_Activity.getAssets().open("credentials.json");
//new FileInputStream(CREDENTIALS_FILE_PATH);
ConnectToDatabase.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(main_Activity.getDir(TOKENS_DIRECTORY_PATH, Context.MODE_APPEND)))
.setAccessType("offline")
.build();
AuthorizationCodeInstalledApp ab = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()){
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
String url = (authorizationUrl.build());
/*flow.newAuthorizationUrl()
.setScopes(flow.getScopes())
.setAccessType("offline")
.setClientId(clientSecrets.getDetails().getClientId())
.setRedirectUri("/oauth2-callback")
.toString();
*/
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
main_Activity.startActivity(browserIntent);
}
};
Credential a = ab.authorize("user");
return a;
}
/**
* Prints the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
public static void main(String[] args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = new com.google.api.client.http.javanet.NetHttpTransport();
final String range = "A1:H";
Sheets service = null;
try {
service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
} catch (IOException e) {
e.printStackTrace();
}
ValueRange response = null;
try {
response = service.spreadsheets().values()
.get(SPREADSHEET_ID, range)
.execute();
} catch (IOException e) {
e.printStackTrace();
}
List<List<Object>> values = response.getValues();
[...]
}
}
您可能需要根据自己的需要修改此代码段。我将其用作我的应用程序的一部分。
那么这段代码会做什么? 执行后,此代码将使用您的个人API密钥连接到google,我将其命名为凭据.json。 (在https://developers.google.com/+/web/api/rest/oauth上创建您自己的) 身份验证成功后,您将可以访问具有特定ID的Google工作表。