【发布时间】:2016-01-15 12:46:12
【问题描述】:
我已成功地将数据从 Google Big Query 移动到 Google Storage 的过程自动化。现在我还需要以自动方式将数据从 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-credentials"
- 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,这里有一些sample code。
标签: java google-api google-cloud-storage google-api-java-client google-authentication