2012-04-18 56 views

回答

2

我不(還)必須通過服務帳戶授權的任何C#示例,但谷歌API的支持服務帳戶授權流程。這裏是(使用與谷歌的BigQuery API此授權流程,在Java & Python中,使用谷歌API客戶端庫爲這些語言的例子http://code.google.com/p/google-api-python-client/和http://code.google.com/p/google-api-java-client/)。用Python實現

import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson.JacksonFactory; 

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 
import com.google.api.services.bigquery.Bigquery; 
import com.google.api.services.bigquery.Bigquery.Datasets; 
import com.google.api.services.bigquery.model.DatasetList; 

import java.io.File; 
import java.io.IOException; 
import java.security.GeneralSecurityException; 


public class BigQueryJavaServiceAccount { 

    private static final String SCOPE = "https://www.googleapis.com/auth/bigquery"; 
    private static final HttpTransport TRANSPORT = new NetHttpTransport(); 
    private static final JsonFactory JSON_FACTORY = new JacksonFactory(); 

    public static void main(String[] args) throws IOException, GeneralSecurityException { 
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(TRANSPORT) 
     .setJsonFactory(JSON_FACTORY) 
     .setServiceAccountId("[email protected]") 
     .setServiceAccountScopes(SCOPE) 
     .setServiceAccountPrivateKeyFromP12File(new File("my_file.p12")) 
     .build(); 

    Bigquery bigquery = Bigquery.builder(TRANSPORT, JSON_FACTORY) 
     .setApplicationName("Google-BigQuery-App/1.0") 
     .setHttpRequestInitializer(credential).build(); 

    Datasets.List datasetRequest = bigquery.datasets().list("publicdata"); 
    DatasetList datasetList = datasetRequest.execute(); 
    System.out.format("%s\n", datasetList.toPrettyString()); 
} 

相同片段:

import httplib2 

from apiclient.discovery import build 
from oauth2client.client import SignedJwtAssertionCredentials 

# REPLACE WITH YOUR Project ID 
PROJECT_ID = 'XXXXXXXXXXX' 
# REPLACE WITH THE SERVICE ACCOUNT EMAIL FROM GOOGLE DEV CONSOLE 
SERVICE_ACCOUNT_EMAIL = '[email protected]' 

f = file('key.p12', 'rb') 
key = f.read() 
f.close() 

credentials = SignedJwtAssertionCredentials(
    SERVICE_ACCOUNT_EMAIL, 
    key, 
    scope='https://www.googleapis.com/auth/bigquery') 

http = httplib2.Http() 
http = credentials.authorize(http) 

service = build('bigquery', 'v2') 
datasets = service.datasets() 
response = datasets.list(projectId=PROJECT_ID).execute(http) 

print('Dataset list:\n') 
for dataset in response['datasets']: 
    print("%s\n" % dataset['id'])