我想将文件从Android设备上传到Google云端存储。为此,我使用JSON API在Google云中创建项目并创建与之相关的存储桶。然后创建服务帐户密钥即p12文件。
但后来又陷入了如何在Android编程中编码的问题。
答案 0 :(得分:0)
private static String uploadFile(RichMedia media) {
DefaultHttpClient client = new DefaultHttpClient();
Bitmap bitmap = BitmapUtils.getBitmap(media.getLocalUrl());
HttpPost post = new HttpPost(GCS_ROOT + media.getLocalUrl() + "_" + System.currentTimeMillis());
if(media.getType() == RichMedia.RichMediaType.PICTURE) {
post.setHeader("Content-Type", "image/jpeg");
} else {
post.setHeader("Content-Type", "video/mp4");
}
post.setHeader("Authorization", "AIzaSyCzdmCMwiMzl6LD7R2obF0xSgnnx5rEfeI");
//post.setHeader("Content-Length", String.valueOf(bitmap.getByteCount()));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
post.setEntity(new StringEntity(new Gson().toJson(byteArray).toString()));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String eachLine = null;
StringBuilder builder = new StringBuilder();
while ((eachLine = reader.readLine()) != null) {
builder.append(eachLine);
}
L.d("response = " + builder.toString());
JSONObject object = new JSONObject(builder.toString());
String name = object.getString("name");
return name;
} catch (IOException e) {
L.print(e);
} catch (JSONException e) {
L.print(e);
}
return null;
}
你可以从这段代码中学习