출처: http://november11tech.tistory.com/88 [Mr.november11] google sheet + java + maven :: 사월은 봄이다.

My naver : https://blog.naver.com/napsis/221462366927

구글 시트를 읽어와야 했다...

후....... 왜 이리 자료가 없노.. 왠지 나중에 또 쓸 수 있으므로...

https://developers.google.com/sheets/api/quickstart/java

여길 보면 퀵 스타트 페이지가 있다. 따라하면 되는데, 구글 sheet api를 발급받아야 한다.

https://console.developers.google.com/flows/enableapi?apiid=sheets.googleapis.com

요기서 하면 된다.











이렇게 발급받는다. 검색해보면 더 자세히 설명해준 사이트도 많음

본격적으로.... 내가 삽질한 부분에 대해 이야기 해 보자면

maven.... 이 생퀴....

계속 import가 안돼서 다른 블로그에서 주로 하는대로 gradle로 하니까 되길래 직접 라이브러리들 비교해서 적어줬다. 그래서 결국...

<!-- google-->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.23.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.23.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-sheets -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>v4-rev516-1.23.0</version>
</dependency>


<!-- https://mvnrepository.com/artifact/jetty/org.mortbay.jetty -->
<!-- https://mvnrepository.com/artifact/jetty/org.mortbay.jetty -->
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mortbay.jetty/jetty-util -->
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>6.1.26</version>
</dependency>

<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5-20081211</version>
</dependency>

<!-- google-->

이걸 다 적어줌... 원래 다른 곳에서는 3개만 디펜던시 걸어주니까 다 알아서 해주던데..... 그냥 내 메이븐이 멍청했던 걸로하자...

gradle의 경우 maven central에서 직접 가지고 오기 때문... 이라고 한다....ㅂㄷㅂㄷ

이제 자바 코드

보면 아까 sheet api를 발급 받을 때 리턴 사이트 주소를 적어줘야 하는데 나 같은 경우는 단순하게

"http://localhost:8080"

라고만 적어줬다가 계속 400이 떴다.

그러다가 밑에 detail 누르니까

http://localhost:8080/Callback

라고 있길래 저래 바꿔주니까 됐음......... 뭐지.... 나만 왜....

암튼 자바 코드를 보면,





import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.ValueRange;
import com.nsuslab.dionysos.promotion.domain.AuthType;
import com.nsuslab.dionysos.promotionPayment.domain.GoogleSheetForm;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import java.util.List;

일단 import 되는건 이정도다.

@RestController
public class PromotionPaymentController {
// OAUTH 2.0 연동시 지정한 OAuth 2.0 클라이언트 이름
private static final String APPLICATION_NAME = "application_name";

// OAUTH 2.0 연동시 credential을 디스크에 저장할 위치
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/sheets.googleapis.com-java-quickstart");

// Global instance of the {@link FileDataStoreFactory}.
private static FileDataStoreFactory DATA_STORE_FACTORY;

// Global instance of the JSON factory.
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

// Global instance of the HTTP transport.
private static HttpTransport HTTP_TRANSPORT;

// Google Sheet API 권한을 SCOPE로 지정
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

// OAUTH 2.0 연동시 사용될 callback용 local receiver 포트 지정
private static final int LOCAL_SERVER_RECEIVER_PORT = 8080;

// HTTP_TRANSPORT, DATA_STORE_FACTORY 초기화
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}

// OAUTH 2.0용 credential
public static Credential getOauth2Authorize() throws IOException {
// OAUTH 2.0용 secret josn 로드
InputStream in = PromotionPaymentController.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();

LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(LOCAL_SERVER_RECEIVER_PORT).build();

Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}

public static Sheets getSheetsService(AuthType authMode) throws IOException {
Credential credential = null;
if (authMode == AuthType.OAUTH20) {
credential = getOauth2Authorize();
}
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}

@PostMapping("/api/google/sheet")
public ResponseEntity RewardPromotions(@RequestBody GoogleSheetForm.Request request) throws IOException {
Sheets service = getSheetsService(AuthType.OAUTH20);
ValueRange response = service.spreadsheets().values()
.get(request.getSpreadSheetId(), request.getRange()).setMajorDimension("ROWS")
.execute();
List<List<Object>> values = response.getValues();
System.out.println(response.getValues().toString());
if (values == null || values.size() == 0) {
System.out.println("No data found.");
} else {
for (List row : values) {
if (row.size() > 0) {
System.out.println(row.get(0).toString());
}
}
}
return new ResponseEntity(HttpStatus.OK);
}

}

public enum AuthType {
OAUTH20
}

간단히 이정도인데 oauth2.0만 했음...

여기서 인증정보를 가진 client_secret.json은 resource 밑에 넣어둔다.









그리고 대충 이런느낌으로 생겼음





이렇게 나온다.

result






참고하면 좋을 사이트들...

https://developers.google.com/sheets/api/samples/reading?hl=ko

만약 기존 oath 키 없애고 새로 발급 받았다면, .credenctial에 저장한 sheets.googleapis.com-java-quickstart 를 삭제한다.

안그러면 401 뜸..










'개발 > JAVA' 카테고리의 다른 글

curreny sign 가져오기  (0) 2019.02.22
Comparator 간단하게 이용하기  (0) 2019.02.05
NullPointerException  (0) 2018.12.24
Java8 함수형  (0) 2018.09.19
Math.random()  (0) 2018.08.07

+ Recent posts