我有一个服务帐户,我将其 Json 文件下载到我的 android studio 的“assets”文件夹中。然后我从谷歌自己的文档中复制/粘贴代码并得到空值。
我尝试了各种方法来读取我的json文件,但都是空的。
void AuthExplicit(){
GoogleCredentials credentials = null;
try {
credentials = GoogleCredentials.fromStream(new FileInputStream("auth.json"))
.createScoped(Lists.newArrayList(Collections.singleton("https://www.googleapis.com/auth/cloud-platform")));
}
catch (IOException e) {
e.printStackTrace();
}
new RefreshCred().execute(credentials);
token = credentials.getAccessToken();
tokenString = token.toString();
}
编辑1 因此,我在 res 下创建了一个 raw 文件夹,并将 auth.json 文件放入其中。然后将我的代码更改为以下。凭据仍然为空。
void AuthExplicit(){
try
{
InputStream stream = getResources().openRawResource(R.raw.auth);
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
token = credentials.getAccessToken();
tokenString = token.toString();
Log.i("Token",tokenString);
new RefreshCred().execute(credentials);
}
catch (IOException e)
{
e.printStackTrace();
}
}
最佳答案
您应该将资源提取到手机上的某个目录,而不是直接从资源文件夹加载。更多详情查看this回答。
关于java - 为什么 GoogleCredentials.fromStream(myJson) 输出为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144941/