11
我已經成功實現了將數據從Google Big Query移至Google Storage的過程自動化。現在我需要以自動的方式將數據從Google Storage下載到我的環境中。使用Java從Google Storage下載文件
我想做一個正常的HTTP請求,但之前授權。所以,我的HTTP請求是
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(authorize());
GenericUrl url = new GenericUrl(uri);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
String content = response.parseAsString();
我的授權碼是
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception
{
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(BigQueryConsumer.class.getResourceAsStream("/secret.json")));
// This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
SCOPES).setDataStoreFactory(fileDataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
凡以下常量是
- CREDENTIALS_DIRECTORY: 「.oauth的憑據」
- JSON_FACTORY:JacksonFactory。 getDefaultInstance()
- SCOPES:剛剛有字符串的列表「https://www.googleapis.com/auth/devstorage.full_control」
- HTTP_TRANSPORT:新NetHttpTransport()
什麼我在身份驗證/授權過程丟失?我越來越
Exception in thread "main" com.google.api.client.http.HttpResponseException: 401 Unauthorized
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
你可能也想嘗試一下。['gcloud-java'(http://googlecloudplatform.github.io/gcloud-java/),這裏的一些[示例代碼(HTTPS: //github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/src/main/java/com/google/gcloud/examples/StorageExample.java)。 –