我需要Google Spreadsheets Java API的帮助。即使我有电子表格,我也会得到一个空的电子表格列表。
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
我的代码中的不会返回任何条目。而当我在浏览器中运行URL http://spreadsheets.google.com/feeds/spreadsheets/private/full
时,我可以看到JSON中的电子表格条目。
这是为什么?我怎样才能解决这个问题?这是我的代码:
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
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.jackson.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 TestSpreadsheet {
private static final String SERVICE_ACCOUNT_EMAIL = "xxx@yyyy-zzzz.iam.gserviceaccount.com";
private static final File SERVICE_ACCOUNT_PKCS12_FILE = new File("./key.p12");
private static SpreadsheetService SPREADSHEETSERVICE;
public static void main(String[] args) throws GeneralSecurityException, IOException, ServiceException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String [] SCOPESArray= {"https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds"};
List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds", "https://spreadsheets.google.com/feeds/spreadsheets/private/full", "https://docs.google.com/feeds");
//final List<String> SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(SERVICE_ACCOUNT_PKCS12_FILE)
.build();
credential.refreshToken();
SPREADSHEETSERVICE = new SpreadsheetService("test");
SPREADSHEETSERVICE.setOAuth2Credentials(credential);
URL SPREADSHEET_FEED_URL;
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = SPREADSHEETSERVICE.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() == 0) {
System.out.println("No spreadsheets found.");
}
}
}
答案 0 :(得分:1)
我找到了解决这个问题的方法。我们需要与服务帐户ID共享电子表格,例如上面的情况xxx@yyyy-zzzz.iam.gserviceaccount.com是服务帐户ID,我们需要与此ID共享电子表格。