Google Data Java Client Library
을 사용하고 OAuth 2.0
에 대한 지원을 Google Spreadsheet API
(현재는 Google Sheets API
)과 함께 사용하는 방법을 보여주는 코드 예는 무엇입니까?Java에서 OAuth 2.0 및 Google Spreadsheet API를 사용하는 예는 무엇입니까?
답변
답변은 원래 질문에서 사이트 "Q and A"형식으로 이동했습니다.
Google Data Java Client Library
OAuth 2.0
을 지원합니다. 불행히도 라이브러리에 Google Spreadsheet API
과 함께 사용하는 방법을 보여주는 완전한 샘플이 없습니다.
다음은 저에게 효과가있는 예입니다. 누군가 도움이되기를 바랍니다. 여기
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
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.util.ServiceException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class NewClass {
// Retrieve the CLIENT_ID and CLIENT_SECRET from an APIs Console project:
// https://code.google.com/apis/console
static String CLIENT_ID = "your-client-id";
static String CLIENT_SECRET = "your-client-secret";
// Change the REDIRECT_URI value to your registered redirect URI for web
// applications.
static String REDIRECT_URI = "the-redirect-uri";
// Add other requested scopes.
static List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds");
public static void main (String args[]) throws IOException, ServiceException, com.google.protobuf.ServiceException{
Credential credencial = getCredentials();
JavaApplication20.printDocuments(credencial);
}
/**
* 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 <--
// 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());
}
// …
}
다른 클래스 :
import com.google.api.client.auth.oauth2.Credential;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.data.spreadsheet.WorksheetFeed;
import com.google.gdata.util.ServiceException;
// ...
import java.io.IOException;
import java.net.URL;
import java.util.List;
// ...
public class JavaApplication20 {
// …
static void printDocuments(Credential credential) throws IOException, ServiceException {
// Instantiate and authorize a new SpreadsheetService object.
SpreadsheetService service =
new SpreadsheetService("Aplication-name");
service.setOAuth2Credentials(credential);
// Send a request to the Documents List API to retrieve document entries.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
SpreadsheetFeed.class);
List<com.google.gdata.data.spreadsheet.SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.isEmpty()) {
// TODO: There were no spreadsheets, act accordingly.
}
com.google.gdata.data.spreadsheet.SpreadsheetEntry spreadsheet = spreadsheets.get(0);
System.out.println(spreadsheet.getTitle().getPlainText());
// Get the first worksheet of the first spreadsheet.
// TODO: Choose a worksheet more intelligently based on your
// app's needs.
WorksheetFeed worksheetFeed = service.getFeed(
spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
// Fetch the cell feed of the worksheet.
URL cellFeedUrl = worksheet.getCellFeedUrl();
CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
// Iterate through each cell, printing its value.
for (CellEntry cell : cellFeed.getEntries()) {
// Print the cell's address in A1 notation
System.out.print(cell.getTitle().getPlainText() + "\t");
// Print the cell's address in R1C1 notation
System.out.print(cell.getId().substring(cell.getId().lastIndexOf('/') + 1) + "\t");
// Print the cell's formula or text value
System.out.print(cell.getCell().getInputValue() + "\t");
// Print the cell's calculated value if the cell's value is numeric
// Prints empty string if cell's value is not numeric
System.out.print(cell.getCell().getNumericValue() + "\t");
// Print the cell's displayed value (useful if the cell has a formula)
System.out.println(cell.getCell().getValue() + "\t");
}
}
// ...
}
이것은 많은 도움이되었습니다. 고마워요. 대부분의 경우 실제로 액세스 토큰이 아닌 새로 고침 토큰을 사용하여 스프레드 시트에 액세스하려고합니다. –
@MosheShaham 제가 생각하기에 : 약 1 시간 후에 액세스 토큰이 만료되고 새로 고침을 사용하여 새 액세스 토큰을 얻어야합니다. 토큰. 안드로이드 응용 프로그램 (설치된 응용 프로그램)에 – eddyparkinson
Google은 클라이언트 ID 만 제공합니다 (클라이언트 비밀 번호는 없음). 내 안드로이드 앱에서 Google 스프레드 시트를 수정하고 싶습니다. 클라이언트 비밀번호없이이 예를 어떻게 사용해야합니까? –
당신은 예 here와 단계의 설명에 의해 단계를 찾을 수 있습니다. 그 결과, 코드는 다음과 같습니다
이SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
service.setProtocolVersion(SpreadsheetService.Versions.V1); // It's important to specify the version
service.setRequestFactory(makeAuthorization());
SpreadsheetQuery q = new SpreadsheetQuery(new URL(DEFAULT_SPREADSHEET_QUERY));
SpreadsheetFeed feed;
try {
feed = service.query(q, SpreadsheetFeed.class);
}
catch (AuthenticationException e) {
refreshAccessToken(service);
feed = service.query(q, SpreadsheetFeed.class);
}
SpreadsheetEntry spreadsheet = findSpreadSheet(feed);
...
// do your stuff
...
// a couple of utility methods are used above:
private void refreshAccessToken(SpreadsheetService service) throws Exception {
String accessToken = callGetAccessTokenApi();
// save access token
service.getRequestFactory().setAuthToken(new GoogleAuthTokenFactory.OAuth2Token(new GoogleCredential().setAccessToken(accessToken)));
}
//private static final String GOOGLE_API_HOST = "https://www.googleapis.com/";
private String callGetAccessTokenApi() throws Exception {
HttpClient client = HttpClients.createDefault();
String url = String.format(
"%soauth2/v3/token?client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token",
GOOGLE_API_HOST,
googleAuthorization.getClientId(),
googleAuthorization.getClientSecret(),
googleAuthorization.getRefreshToken()
);
HttpPost post = new HttpPost(url);
post.addHeader(ACCEPT_HEADER_NAME, "application/x-www-form-urlencoded");
try {
HttpResponse response = client.execute(post);
JSONObject object = readJson(response);
return object.getString("access_token");
}
finally {
post.releaseConnection();
}
}
private Service.GDataRequestFactory makeAuthorization() {
Service.GDataRequestFactory requestFactory = new HttpGDataRequest.Factory();
// load access token
requestFactory.setAuthToken(new GoogleAuthTokenFactory.OAuth2Token(new GoogleCredential().setAccessToken(accessToken)));
return requestFactory;
}
이 질문의 대부분 (2016 진수) 대부분의 해답이 여기 지금 오래된로 : 1) GData APIs 구글의 이전 세대 아피스. 모든 GData API가 지원되지 않지만 all modern Google APIs은 이 아니며은 the Google Data protocol입니다. 2) Google released a new Google Sheets API v4 (GData 제외)을 2016 년에 사용해야합니다. 새 API를 사용하려면 the Google APIs Client Library for Java을 가져와 최신 API 인 Sheets API을 사용해야합니다. 이는 이전 API보다 훨씬 강력하고 유연합니다.
여기 API를 계속 사용하는 데 도움이되는 our Java Quickstart code sample이 있습니다. OAuth2 코드도 있습니다. 또한 여기에 모든 수업을 대략적으로 설명하는 the JavaDocs reference for the Sheets API이 있습니다.
- Accessing Google APIs: Common code walkthrough (: 당신은 "알레르기"파이썬에하지 않은 경우, 나는 또한의 OAuth 인증 코드와 시트 API를 사용하여 더 많은 "실제"예와 비디오의 또 다른 한 쌍을 걷는 비디오를했습니다 OL에서 사용할 수
- Migrating SQL data to a Sheet (코드 심도있는 post)
- Formatting text using the Sheets API (코드 심도있는 post)
최신 API가 제공하는 기능 코드가 아닌 깊은 다이빙 post) 사용자 인터페이스 (고정 된 행 만들기, 셀 서식 지정, 행/열 크기 조정, 피벗 테이블 추가, 차트 만들기 등)를 사용하는 것처럼 개발자가 시트에 프로그래밍 방식으로 액세스 할 수있게 해줍니다. 또한이 API는 주로 프로그래밍 방식의 스프레드 시트 작업 & 기능을 사용할 수 있습니다.
내가 '예 한 쌍은 여기에 대신 Google Drive API을 사용, 수입에게, & 수출 (& 다운로드하지만, 변환/다양한 형식의 업로드와 같은)를 같은 업로드 &로 다운로드 할 파일 수준의 액세스를 수행하고 했습니다 (파이썬) 생성 :
(*) - TL : DR : 일반 텍스트 파일을 드라이브에 업로드하고 Google 문서 형식으로 가져 오거나 변환 한 다음 해당 문서를 PDF로 내 보냅니다. 위의 게시물은 Drive API v2를 사용합니다. this follow-up post은 드라이브 API v3으로 이전하는 것에 대해 설명합니다. 두 게시물을 모두 합치는 developer video입니다.
Google API (대부분 Python 또는 JavaScript)를 사용하는 방법에 대해 자세히 알아 보려면 다양한 Google 개발자 비디오 (series 1 및)를 확인하십시오.
- 1. Google 이메일 설정 Java에서 OAuth 2.0 서비스 계정을 사용하는 API
- 2. Google API 및 OAuth 2.0
- 3. Passport.js Bearer를 사용하는 OAuth 2.0
- 4. Java에서 AIR 2.0 NativeProcess API를 사용하는 방법?
- 5. oAuth 2.0 API를 통한 C#
- 6. Google API OAuth 2.0
- 7. .Net에있는 YouTube 및 OAuth 2.0
- 8. Socialauth API 4.3 with Google Oauth 2.0
- 9. OAuth 2.0없이 Google 캘린더 API를 사용하는 방법
- 10. Facebook 및 OAuth 2.0
- 11. Google OAuth 2.0 특정 도메인
- 12. Google OAuth 2.0 구현 - 등록
- 13. Google OAuth 2.0 with android
- 14. Android에서 OAuth 2.0을 사용하여 Google API를 사용하는 가장 좋은 방법은
- 15. Facebook Canvas Application 그래프 API를 사용하는 iFrame OAuth 2.0
- 16. 브라우저없이 Google OAuth 2.0 로그인
- 17. Google OAuth 2.0 콜백 URL
- 18. oauth 2.0 on appspot.com
- 19. php api를 사용하여 Google 캘린더에 동적으로 인증 OAuth 2.0 사용
- 20. Java에서 Google 시각화 API를 사용하는 방법이 있습니까
- 21. google 캘린더를 사용하는 반복 - OnlyOnWeeks의 예는 무엇입니까?
- 22. 조각과 Google Analytics를 사용하는 예는 무엇입니까?
- 23. 자바 스크립트에서 REST Oauth 2.0 API를 안전하게 사용하는 방법
- 24. Google 드라이브 API OAuth 2.0; 오류 : origin_mismatch
- 25. Google 앱용 API를 사용하는 목적이
- 26. Google 드라이브 API 통합을위한 Google OAuth 2.0 리디렉션 방지
- 27. OAuth 2.0 및 해당 사양
- 28. Google Play 서비스 인증 (oauth 2.0)
- 29. OAuth 2.0 및 Amazon Beanstalk
- 30. Google OAuth 2.0 서비스 계정 인증
좋아요. 아마도 코드를 추가하여 새로 고침 토큰에서 액세스 토큰을 가져올 수 있습니다. ... 또한 이것을 질문 및 응답 형식으로 변환하는 것이 적합 할 것입니다. – eddyparkinson
흠, 이것이 질문으로 가장 한 대답입니까?! ... 나는 이것을 Q와 A로 재구성 할 것이라고 생각합니다. – ErstwhileIII