我有客户端/服务器应用程序。服务器端必须访问我自己的 Google 云端硬盘上的电子表格。我创建了一个测试类来尝试访问电子表格列表:
package com.eng.app;
import java.io.File;
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
public class TestGoogleCredential {
public static void main(String[] args) throws IOException,
InterruptedException, GeneralSecurityException, URISyntaxException, ServiceException {
List<String> SCOPES = Arrays
.asList("https://spreadsheets.google.com/feeds");
final HttpTransport TRANSPORT = new NetHttpTransport();
final JsonFactory JSON_FACTORY = new JacksonFactory();
File cert = new File(Credential.class.getClassLoader()
.getResource("<the_file>.p12").toURI());
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(<email-address>)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(cert).build();
SpreadsheetService service = new SpreadsheetService("Inertia");
service.setOAuth2Credentials(credential);
String urlString = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";
URL SPREADSHEET_FEED_URL = new URL(urlString);
// istantiate the feed to the spreadsheets
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,SpreadsheetFeed.class);
// the list of all spreadsheets
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
System.out.println(feed.getEntries().size());
// select the particular spreadsheet on Inertia Ontology
for (SpreadsheetEntry spreadsheetEntry : spreadsheets) {
System.out.println("founded");
}
}
}
但是当我运行代码时,大小为 0,并且没有打印出电子表格。
我还进行了另一个测试,编写了一个程序,该程序使用我的Google凭据而不是OAuth2授权访问(在本地主机上)电子表格列表,并且效果很好(它可以在我的Google云端硬盘上打印出我的所有电子表格)。
service.setUserCredentials(username, password); //My personal Google Account
注意:当我使用我的个人Google凭据(不是OAuth2)在远程服务器上部署测试程序时,Google阻止了安全策略。
请问有什么想法吗?
谢谢
尝试修改此代码段
GoogleCredential credential = new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId("google-dev-console-email-address") .setServiceAccountUser("your-gmail") .setServiceAccountScopes(SCOPES) .setServiceAccountPrivateKeyFromP12File(cert).build();