gpt4 book ai didi

java - 在 Java Spring 中获取资源 URL 路径

转载 作者:行者123 更新时间:2023-11-30 02:44:51 24 4
gpt4 key购买 nike

尝试获取资源文件夹中的 JSON 文件的路径,但使用 getResource().getPath() 失败。我希望以尽可能可靠的方式获取此 URL。

public static void initializeFirebase() {
try {
URL url = getResource("google-services.json");
System.out.println(url.getPath());
FirebaseOptions options = new FirebaseOptions
.Builder()
.setServiceAccount(new FileInputStream(url.getPath()))
.setDatabaseUrl("https://XXXXX.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
} catch (IOException e) {
e.printStackTrace();
}

}

上面的函数打印:/Users/username/Documents/Spring_Project/springbackend/build/resources/main/google-services.json 在抛出错误之前:

Exception in thread "main" java.lang.RuntimeException: Failed to read service account
at com.google.firebase.FirebaseOptions$Builder.setServiceAccount(FirebaseOptions.java:82)
at live.cibc.labs.springbackend.SpringbackendApplication.initializeFirebase(SpringbackendApplication.java:188)
at live.cibc.labs.springbackend.SpringbackendApplication.main(SpringbackendApplication.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.json.JSONException: JSONObject["project_id"] not found.

显然它找不到我的project_id,因为我的google-services.json位于src/main/resources/google-services.json下。

我应该如何以尽可能健壮的方式获取路径?

google-services.json

{
"project_info": {
"project_number": "XXXXXXXX",
"firebase_url": "https://XXXXXX.firebaseio.com",
"project_id": "XXXX-XXX",
"storage_bucket": "XXXXXXXX.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:XXXXXXXXX:android:XXXXXXX",
"android_client_info": {
"package_name": "my.spring.project"
}
},
"oauth_client": [
{
"client_id": "XXXXX-XXXXX.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "XXXXXX"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 1,
"other_platform_oauth_client": []
},
"ads_service": {
"status": 2
}
}
}
],
"configuration_version": "1"
}

最佳答案

我的答案最终变得非常愚蠢!在 Firebase 控制台中,您可以下载 2 个 JSON 文件。

  • google-services.json 用于客户端
  • service-account-credentials.json 用于服务器管理 SDK(我应该使用的那个)

不要混淆两者!

关于java - 在 Java Spring 中获取资源 URL 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com