Zan*_*hna 3 android json google-api-java-client google-cloud-storage
我想Google Cloud Storage
从我的Android应用程序上传图像.为此,我搜索并发现GCS JSON Api
提供此功能.我做了大量针对Android示例的研究,展示了它的用途.在开发人员站点上,他们提供了仅支持java的代码示例.我不知道如何在Android中使用该API.我提到了这个和这个链接,但无法理解.请指导我如何使用这个api与Android应用程序.
好的,所以我解决了它,并将我的图像上传到云存储中都很好.这是如何:
注意:我使用XML API几乎是一样的.
首先,您需要下载大量库.最简单的方法是创建一个maven项目,让它下载所需的所有依赖项.从此示例项目: 示例项目 库应该是:
其次,您必须熟悉使用api控制台的云存储 您必须创建项目,创建存储桶,授予存储桶权限等.您可以在此处找到有关它的更多详细信息
第三,一旦你准备好所有这些东西,就该开始编码了.假设我们要上传图片:云端存储可与OAuth配合使用,这意味着您必须是经过身份验证的用户才能使用该API.为此,最好的方法是授权使用服务帐户.不用担心,你唯一需要做的就是在API控制台中获得一个这样的服务帐户:
我们将在代码中使用此服务帐户.
第四,让我们写一些代码,让我们说将图像上传到云存储.要使此代码生效,您必须将步骤3中生成的密钥放在assets文件夹中,我将其命名为"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);}
Run Code Online (Sandbox Code Playgroud)
这会将图像上传到您的云端桶.
有关api的更多信息,请查看此链接Cloud XML API