2012-05-30 91 views
0

我嘗試了許多不同的操作來訪問Google帳戶以讀取配置文件數據,但每次都失敗。Java Google Plus通過oAuth 2.0訪問

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized 
{ 
    "code" : 401, 
    "errors" : [ { 
    "domain" : "global", 
    "location" : "Authorization", 
    "locationType" : "header", 
    "message" : "Invalid Credentials", 
    "reason" : "authError" 
    } ], 
    "message" : "Invalid Credentials" 
} 

我想通過以下代碼訪問

@SuppressWarnings("deprecation") 
public static GoogleAccessProtectedResource connect(String CLIENT_ID,String CLIENT_SECRET,String SCOPE,String CALLBACK_URL,HttpTransport TRANSPORT,JsonFactory JSON_FACTORY) throws IOException{ 
    // Generate the URL to which we will direct users 
     String authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID, 
      CALLBACK_URL, SCOPE).build(); 
     System.out.println("Paste this url in your browser: " + authorizeUrl); 

     // Wait for the authorization code 
     System.out.println("Type the code you received here: "); 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     String authorizationCode = in.readLine(); 

     // Exchange for an access and refresh token 
     GoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(TRANSPORT, 
      JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authorizationCode, CALLBACK_URL); 
     authRequest.useBasicAuthorization = false; 
     AccessTokenResponse authResponse = authRequest.execute(); 
     String accessToken = authResponse.accessToken; 
     GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, 
      TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authResponse.refreshToken); 
     HttpRequestFactory rf = TRANSPORT.createRequestFactory(access); 
     System.out.println("Access token: " + authResponse.accessToken); 

     // Make an authenticated request 
     GenericUrl shortenEndpoint = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url"); 
     String requestBody = 
      "{\"longUrl\":\"http://farm6.static.flickr.com/5281/5686001474_e06f1587ff_o.jpg\"}"; 
     HttpRequest request = rf.buildPostRequest(shortenEndpoint, 
      ByteArrayContent.fromString("application/json", requestBody)); 
     HttpResponse shortUrl = request.execute(); 
     BufferedReader output = new BufferedReader(new InputStreamReader(shortUrl.getContent())); 
     System.out.println("Shorten Response: "); 
     for (String line = output.readLine(); line != null; line = output.readLine()) { 
      System.out.println(line); 
     } 

     // Refresh a token (SHOULD ONLY BE DONE WHEN ACCESS TOKEN EXPIRES) 
     //access.refreshToken(); 
     //System.out.println("Original Token: " + accessToken + " New Token: " + access.getAccessToken()); 

     return access; 


    } 

然後我想訪問我的帳戶

public static void getData1(String accessToken, String clientId, String clientSecret, String refreshToken) throws IOException{ 
    // Set up the HTTP transport and JSON factory 
     HttpTransport httpTransport = new NetHttpTransport(); 
     JsonFactory jsonFactory = new JacksonFactory(); 

     // Set up OAuth 2.0 access of protected resources 
     // using the refresh and access tokens, automatically 
     // refreshing the access token when it expires 
     GoogleAccessProtectedResource requestInitializer = 
      new GoogleAccessProtectedResource(accessToken, httpTransport, 
      jsonFactory, clientId, clientSecret, refreshToken); 

     // Set up the main Google+ class 
     Plus plus = Plus.builder(httpTransport, jsonFactory) 
      .setHttpRequestInitializer(requestInitializer) 
      .build(); 

     // Make a request to access your profile and display it to console 
     Person profile = plus.people().get("[myID]").execute(); 
     System.out.println("ID: " + profile.getId()); 
     System.out.println("Name: " + profile.getDisplayName()); 
     System.out.println("Image URL: " + profile.getImage().getUrl()); 
     System.out.println("Profile URL: " + profile.getUrl()); 
    } 

主要有以下方法應該工作算賬:CLIENT_IDCLIENT_SECRET創建

public static void main(String[] args) throws IOException { 
    GoogleAccessProtectedResource access1=Connection.connect(CLIENT_ID, CLIENT_SECRET, SCOPE, CALLBACK_URL, TRANSPORT, JSON_FACTORY); 

    //refresh 
    String token= access1.getAccessToken(); 
    access1.refreshToken(); 
    String refreshed=access1.getAccessToken(); 
//get data 
    Connection.getData1(token, CLIENT_ID, CLIENT_SECRET, refreshed); 
} 

這是我的數據...

private static final String SCOPE = "https://www.googleapis.com/auth/urlshortener"; 
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob"; 
private static final HttpTransport TRANSPORT = new NetHttpTransport(); 
private static final JsonFactory JSON_FACTORY = new JacksonFactory(); 

// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLE 
private static final String CLIENT_ID = "[myID].apps.googleusercontent.com"; 
private static final String CLIENT_SECRET = "[myID]"; 

現在有一個不好的請求拋出異常

Exception in thread "main" com.google.api.client.http.HttpResponseException: 400 Bad Request 
{ 
"error" : "invalid_client" 
} 
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:900) 
at com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.executeUnparsed(AccessTokenRequest.java:472) 
at com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.execute(AccessTokenRequest.java:486) 
at Connection.connect(Connection.java:78) 
at Connection.main(Connection.java:50) 
+0

是你的代碼運行? –

+0

它現在工作! 我無法解釋出了什麼問題,我複製粘貼了祕密和祕密,它的工作。 但是,如果你使用谷歌加Java初學者項目,它會更好,更容易:https://code.google.com/p/google-plus-java-starter/ – hannes

回答

1

這是希望很容易修復。

您使用的範圍字符串:

https://www.googleapis.com/auth/urlshortener

這是URL縮短服務(goo.gl)API,而不是Google+的API的範圍。相反,你應該嘗試使用該配置文件範圍爲Google+的

https://www.googleapis.com/auth/plus.me

文檔瀏覽: https://developers.google.com/+/api/oauth

上面,它看起來像你使用[身份識別碼]引用兩種不同類型的ID:

在以下聲明中,myID應該是您的Google+個人資料ID(從Google+個人資料的網址複製/粘貼,或者使用字符串'me'代表當前的授權用戶):

Person profile = plus.people().get("[myID]").execute();

然而,對於CLIENT_ID,你應該使用在code.google.com/apis/console項目的值。

+0

謝謝瑞安,我試着用你的建議解決它,但它不起作用... 我改變了你提到的範圍。 對於[myID],我使用了兩種不同類型的ID。我只想隱藏它們;) – hannes

+0

你現在看到什麼例外,你正在使用正確的範圍? –

+0

我在下面添加了對此主題的新答案,因爲它無法將代碼發佈到評論中! HttpResponseException被拋出。順便說一句, 。我正在研究我的學士論文,我需要在Google+上導出我的個人資料的個人資料數據。 這是正確的方法嗎? – hannes