Google 云存储 md5 检查文件

Google cloud storage md5 check on file

我想获取我的 GCS 文件的内容 md5。

我试过这样做:

Storage.Objects.Get get = storage.objects().get(BUCKET_NAME_MUSIC_DATA, fileName);
serverHash = get.execute().getMd5Hash();
bufferedInputStream = new BufferedInputStream(get.executeMediaAsInputStream());
//process the stream

我得到了 md5 和流,但这在技术上涉及 2 个网络调用。

然后我尝试了这个:

Storage.Objects.Get get = storage.objects().get(BUCKET_NAME_MUSIC_DATA, fileName);
HttpResponse httpResponse = get.executeMedia();
serverHash = httpResponse.getHeaders().getContentMD5();
bufferedInputStream = new BufferedInputStream(httpResponse.getContent());

这是一个单一的网络调用,但散列为空.... 请帮助。

好的,我在阅读文档后找到了解决方案。 md5 散列在 x-goog-hash header 键中。 这是代码:

Storage.Objects.Get get = storage.objects().get(BUCKET_NAME_APP_DATA, fileName);
HttpResponse httpResponse = get.executeMedia();
String x_goog_hash = httpResponse.getHeaders().get("x-goog-hash").toString().replaceAll("\s+","");
if (TextUtils.isEmpty(x_goog_hash))
    throw new IOException("Response x-goog-hash was null");

final int start = x_goog_hash.indexOf("md5=");
final int end = x_goog_hash.indexOf("==", start);

if (start == -1 || end == -1 || end <= start)
    throw new IOException("Response x-goog-hash of unexpected type " + x_goog_hash);

serverHash = x_goog_hash.substring(start + 4, end + 2);
if (TextUtils.isEmpty(serverHash))
    throw new IOException("Response md5 was null");

Log.i("Ayush", "Md5 hash = ? " + serverHash);
bufferedInputStream = new BufferedInputStream(httpResponse.getContent());