在Android中使用Google Cloud Storage JSON API

4
我希望能够在我的Android应用程序中从Google Cloud Storage上传图像。 为此,我搜索并发现GCS JSON Api提供了这个功能。 我进行了大量研究,寻找可以演示其使用的Android示例。 在开发者网站上,他们提供的代码示例仅支持Java。 我不知道如何在Android中使用该API。 我参考了这个这个链接,但是没有得到很多想法。 请指导我如何在Android应用程序中使用此API。

你找到什么了吗?@zanky? - chelo_c
1
@chelo_c 不是,我使用Blobstore将图片存储在Google Cloud上。 - Zankhna
2个回答

10

好的,大家好,我已经解决了这个问题,并成功将我的图片上传到了云存储中。

注意:我使用了XML API,它基本上是相同的。

首先,您需要下载许多库。最简单的方法是创建一个Maven项目并让它下载所需的所有依赖项。从这个示例项目: 示例项目 所需的库包括:

enter image description here

第二,您必须熟悉使用API控制台的Cloud Storage。 您必须创建一个项目、创建一个bucket、给bucket权限等等。您可以在这里找到更多详细信息。

第三,一旦您准备好所有这些事项,就是开始编写代码的时候了。假设我们想上传一张图片: Cloud Storage使用OAuth,这意味着您必须是经过身份验证的用户才能使用API。为此,最好的方法是使用服务帐户进行授权。不要担心,您只需要在API控制台中获取一个像这样的服务帐户:

enter image description here

我们将在代码中使用此服务帐户。

第四,让我们编写一些代码,例如上传图片到云存储。 为了使此代码工作,您必须将在步骤3中生成的密钥放入资产文件夹中,我将其命名为“key.p12”。

我不建议您在生产版本上这样做,因为您将会泄露您的密钥。

try{
httpTransport= new com.google.api.client.http.javanet.NetHttpTransport();


//agarro la key y la convierto en un file
AssetManager am = context.getAssets();
InputStream inputStream = am.open("key.p12"); //you should not put the key in assets in prod version.



//convert key into class File. from inputstream to file. in an aux class.
File file = UserProfileImageUploadHelper.createFileFromInputStream(inputStream,context);


//Google Credentianls
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
        .setServiceAccountPrivateKeyFromP12File(file)
        .build();




String URI = "https://storage.googleapis.com/" + BUCKET_NAME+"/"+imagename+".jpg";
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);


GenericUrl url = new GenericUrl(URI);




//byte array holds the data, in this case the image i want to upload in bytes.

HttpContent contentsend = new ByteArrayContent("image/jpeg", byteArray );


HttpRequest putRequest = requestFactory.buildPutRequest(url, contentsend);



com.google.api.client.http.HttpResponse response = putRequest.execute();
String content = response.parseAsString();
Log.d("debug", "response is:"+response.getStatusCode());
Log.d("debug", "response content is:"+content);} catch (Exception e) Log.d("debug", "Error in  user profile image uploading", e);}

这将把图像上传到您的云存储桶中。

有关 API 的更多信息,请查看此链接:Cloud XML API


@Cristiana214 我还没有进入生产阶段,所以我还没有考虑过这个问题。但问题在于,如果你泄露了p12密钥,其他人就能够访问API。 - chelo_c
你能否提供所有的代码?例如,我不知道JSON_FACTORY、STORAGE_SCOPE是什么? - tamtoum1987
@tamtoum1987,你问的不是我的代码,那是依赖项自带的。 - chelo_c
@chelo_c 请问需要哪些依赖?我在Android中没有使用Maven,我能在Maven依赖中找到源代码吗? - tamtoum1987
@tamtoum1987,它说: "首先,您需要下载许多库。最简单的方法是创建一个Maven项目并让它下载所需的所有依赖项。" 您完成了这一步吗? - chelo_c
显示剩余5条评论

0
首先,您应该通过在GCP控制台中注册您的应用程序来获取以下信息。
private final String pkcsFile = "xxx.json";//private key file
private final String bucketName = "your_gcp_bucket_name";
private final String projectId = "your_gcp_project_id";

一旦您获得了凭据,您应该将私钥(.p12或.json)放在资产文件夹中。我正在使用JSON格式的私钥文件。另外,您应该更新图像位置以上传。

@RequiresApi(api = Build.VERSION_CODES.O)
    public void uploadImageFile(String srcFileName, String newName) {
            Storage storage = getStorage();

        File file = new File(srcFileName);//Your image loaction
        byte[] fileContent;
        try {
            fileContent = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (fileContent == null || fileContent.length == 0)
            return;
        BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of(bucketName), newName);
        BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
        Blob blob = storage.create(blobInfo, fileContent);
        String bucket = blob.getBucket();
        String contentType = blob.getContentType();
        Log.e("TAG", "Upload File: " + contentType);
        Log.e("File ", srcFileName + " uploaded to bucket " + bucket + " as " + newName);
    }

private Storage getStorage() {
        InputStream credentialsStream;
        Credentials credentials;

        try {
            credentialsStream = mContext.getAssets().open(pkcsFile);
            credentials = GoogleCredentials.fromStream(credentialsStream);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return StorageOptions.newBuilder()
                .setProjectId(projectId).setCredentials(credentials)
                .build().getService();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接