java - 将 Google Drive API 与 scala play 项目一起使用
问题描述
我一直在尝试调整 java 快速入门指南,以便与 Scala Play 项目的谷歌驱动 API 进行交互,但是我在读取凭证文件时遇到问题,它说它不存在,但我尝试过:
- 绝对路径
- 来自内容根目录的路径
- 来自源根的路径
但这些都没有奏效。
这是我的项目结构: 项目结构
这是错误: 错误
这是我用来尝试读取文件的代码:
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, GoogleClientSecrets}
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.javanet.NetHttpTransport
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.SheetsScopes
import java.io.{File, FileNotFoundException, IOException, InputStreamReader}
import java.security.GeneralSecurityException
import java.util
import java.util.Collections
class GoogleService {
private val applicationName: String = "Google Sheets API Java Quickstart"
private val jsonFactory: JsonFactory = JacksonFactory.getDefaultInstance()
private val tokenDirectoryPath: String = "tokens"
private val scopes: util.List[String] = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY)
private val credentialsFilePath: String = "app/assets/credentials.json"
@throws[IOException]
private def getCredentials(HTTP_TRANSPORT: NetHttpTransport) = { // Load client secrets.
val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)
if (in == null) {
System.out.printf(credentialsFilePath)
throw new FileNotFoundException(s"Resource not found: $credentialsFilePath")
}
val clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(in))
// Build flow and trigger user authorization request.
val flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, jsonFactory, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(new File(tokenDirectoryPath))).setAccessType("offline").build
val receiver = new LocalServerReceiver.Builder().setPort(8888).build
new AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
}
@throws[IOException]
@throws[GeneralSecurityException]
def main(args: String*
) {
val httpTransport = GoogleNetHttpTransport.newTrustedTransport
getCredentials(httpTransport)
}
}
解决方案
尝试替换:
val in = classOf[GoogleService].getResourceAsStream(credentialsFilePath)
和:
val in = getClass.getResourceAsStream(credentialsFilePath)
请注意,资源通常位于conf
文件夹中,这是查找它们的地方。请尝试将文件夹assets
从app
文件夹重定位到conf
. 然后更新:
private val credentialsFilePath: String = "assets/credentials.json"