在 Java 中的 Google Drive 中使用 Google Spreadsheet API 创建电子表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30483601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Spreadsheet using Google Spreadsheet API in Google drive in Java
提问by Skwarosz
I had created some tool which was populating the google spreadsheet. It was working fine for 1 year, since today I've error
我创建了一些填充谷歌电子表格的工具。它工作正常 1 年,因为今天我出错了
Exception in thread "main" com.google.gdata.util.AuthenticationException: Error authenticating (check service name)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:688)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
This is the part of code to connect with gmail:
这是与 gmail 连接的代码部分:
String USERNAME = "[email protected]"; ->of course I'm using proper username and password
String PASSWORD = "*******";
SpreadsheetService service
= new SpreadsheetService("SandboxCheck");
service.setUserCredentials(USERNAME, PASSWORD);
I don't know how to connect with gmail, I was trying to do this via oAuth but I don't know how to do this. In examples on https://developers.google.com/google-apps/spreadsheets/authorizethere is only code for .net.
我不知道如何与 gmail 连接,我试图通过 oAuth 做到这一点,但我不知道如何做到这一点。在https://developers.google.com/google-apps/spreadsheets/authorize上的示例中,只有 .net 的代码。
回答by Skwarosz
I finally with help from heremanaged to create such connection. Everything is working as before. Steps You have to do is:
我终于在这里的帮助下设法建立了这种联系。一切都像以前一样工作。你要做的步骤是:
- Register at https://console.developers.google.com
- Create new project
- Under APIs & Auth -> Credential -> Create New Client ID for Service Account
- When the Client ID is generated You have to generate P12 key.
- Client id will be needed in code below, Email addres is the addres You have to share Your spreadsheet
- 在https://console.developers.google.com注册
- 创建新项目
- 在 APIs & Auth -> Credential -> Create New Client ID for Service Account
- 生成客户端 ID 时,您必须生成 P12 密钥。
- 下面的代码将需要客户 ID,电子邮件地址是您必须共享电子表格的地址
Below is the working code
下面是工作代码
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.Hymanson.HymansonFactory;
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 OAuthIntegration{
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();
HymansonFactory jsonFactory = new HymansonFactory();
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);
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);
}
}
}
}
I hope this will help with issues I've faced. This is the list of jar I've used:
我希望这将有助于解决我遇到的问题。这是我使用过的 jar 列表:
guava-11.0.2.jar
gdata-spreadsheet-3.0.jar
gdata-maps-2.0.jar
gdata-core-1.0.jar
Hymanson-core-asl-1.9.11.jar
Hymanson-core-2.1.3.jar
google-oauth-client-1.20.0.jar
google-http-client-Hymanson2-1.20.0.jar
google-http-client-Hymanson-1.20.0.jar
google-http-client-1.20.0.jar
google-api-client-1.20.0.jar
回答by Gao
Google just stopped support OAuth1.0. OAuth2 needs to be used. To switch, first go to Google Developer Console, create a project and set a credential. Then update your code similar to the following Java code:
Google 刚刚停止支持 OAuth1.0。需要使用 OAuth2。要切换,请先转到 Google Developer Console,创建一个项目并设置凭据。然后更新类似于以下 Java 代码的代码:
private void createSpreadSheetService() throws GeneralSecurityException, IOException, ServiceException {
HttpTransport httpTransport = new NetHttpTransport();
HymansonFactory jsonFactory = new HymansonFactory();
String [] SCOPESArray= {"https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds"};
final List 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();
SPREADSHEETSERVICE = new SpreadsheetService("data");
SPREADSHEETSERVICE.setOAuth2Credentials(credential);
}
}
You would need two libraries: google-api-client and google-http-client-Hymanson. If you use Maven, including the following dependencies in pom.xml.
您需要两个库:google-api-client 和 google-http-client-Hymanson。如果使用Maven,在pom.xml中包含如下依赖。
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.19.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-Hymanson</artifactId>
<version>1.19.0</version>
<type>jar</type>
</dependency>
回答by Skwarosz
I've tried solution from Gao but I have one problem with Libraries. I'm using netbeans, the project is building without error but when I'm trying to execute it I've this error:
我已经尝试过 Gao 的解决方案,但图书馆有一个问题。我正在使用 netbeans,该项目正在构建时没有错误,但是当我尝试执行它时,出现了以下错误:
Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/Hymanson/JsonFactory
at com.google.api.client.json.Hymanson.HymansonFactory.<init>(HymansonFactory.java:38)
at SandboxCheck.main(SandboxCheck.java:48)
I found out that there are problem with classpath but I have no idea how to fix it on netbeans, I thought it would do it automatically when adding a library. I've added
我发现类路径有问题,但我不知道如何在 netbeans 上修复它,我认为它会在添加库时自动完成。我已经添加
google-oauth-client-1.16.0-rc.jar google-oauth-client-1.16.0-rc-sources.jar google-api-client-1.8.0-beta-sources.jar google-api-client-1.4.1-beta.jar google-api-client-1.19.1.jar
google-oauth-client-1.16.0-rc.jar google-oauth-client-1.16.0-rc-sources.jar google-api-client-1.8.0-beta-sources.jar google-api-client-1.4.1-beta.jar google-api-client-1.19.1.jar
I'm not sure If I add too much of this libraries but If I remove for eg. google-api-client-1.4.1-beta.jar it won't see HymansonFactory class.
我不确定我是否添加了太多这个库,但是如果我删除了例如。google-api-client-1.4.1-beta.jar 它不会看到 HymansonFactory 类。