我从here举了示例。但是下面的代码给了我" 方法setOAuth2Credentials(GoogleCredential)未定义为SpreadsheetService "。
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;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class Main{
public static void main(String[] args) throws MalformedURLException, GeneralSecurityException, IOException, ServiceException {
URL SPREADSHEET_FEED_URL;
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
File p12 = new File("./key.p12");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
String[] SCOPESArray = {"https://spreadsheets.google.com/feeds", "https://spreadsheets.google.com/feeds/spreadsheets/private/full", "https://docs.google.com/feeds"};
final List SCOPES = Arrays.asList(SCOPESArray);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("cliend_ID")
.setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(p12)
.build();
SpreadsheetService service = new SpreadsheetService("Test");
service.setOAuth2Credentials(credential); /////// Error occurs here "The method setOAuth2Credentials(GoogleCredential) is undefined for the type SpreadsheetService"
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() == 0) {
System.out.println("No spreadsheets found.");
}
SpreadsheetEntry spreadsheet = null;
for (int i = 0; i < spreadsheets.size(); i++) {
if (spreadsheets.get(i).getTitle().getPlainText().startsWith("ListOfSandboxes")) {
spreadsheet = spreadsheets.get(i);
System.out.println("Name of editing spreadsheet: " + spreadsheets.get(i).getTitle().getPlainText());
System.out.println("ID of SpreadSheet: " + i);
}
}
}
}
我只是复制了代码并导入了所提到的库,但我不明白为什么我会收到如下错误。
答案 0 :(得分:1)
检查您是否使用了正确版本的依赖项:
<dependency>
<groupId>com.google.gdata</groupId>
<artifactId>core</artifactId>
<version>1.47.1</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.20.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.20.0</version>
</dependency>