我希望从Google Spreadsheets中读取数据。以下是我到目前为止所尝试的事情:
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.*;
import java.util.*;
public class MySpreadsheetIntegration1 {
public static void main(String[] args)
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service =
new SpreadsheetService("SpreadSheetSample");
// TODO: Authorize the service object for a specific user (see other sections)
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://docs.google.com/spreadsheets/d/1jeo8zOv34wVmIX3rL48GksZgj0ixgHx_cwDCdZyQKCg/edit#gid=0");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
}
当我运行此代码时,我得到连接超时错误。我觉得这是一些身份验证问题。
有人可以帮我解决一下这个问题吗?
Here是我为测试目的而创建的电子表格的链接。 谷歌也提供了很多代码,但到目前为止它们都没有。
答案 0 :(得分:1)
因此,您需要实际创建一个OAuth会话,以便通过Google验证自己。
以下是我用于当前项目的OAuth代码!
/**
* Retrieve OAuth 2.0 credentials.
*
* @return OAuth 2.0 Credential instance.
*/
static Credential getCredentials() throws IOException {
HttpTransport transport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
// Step 1: Authorize -->
String authorizationUrl =
new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();
// Point or redirect your user to the authorizationUrl.
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Read the authorization code from the standard input stream.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String code = in.readLine();
// End of Step 1 <--
// Step 2: Exchange -->
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
code, REDIRECT_URI).execute();
// End of Step 2 <--
authenticated = true;
// Build a new GoogleCredential instance and return it.
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
}
然后你就这么称呼它
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setOAuth2Credentials(getCredentials());