2012-05-30 4 views
0

프로필 데이터를 읽기 위해 Google 계정에 액세스하는 데 여러 가지 시도를했지만 항상 실패했습니다.oAuth 2.0을 통한 Java Google Plus 액세스

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

지금 작동 중! 나는 무엇이 잘못되었는지 설명 할 수 없다. 나는 clientid와 secret를 다시 붙여 넣는다. 구글 플러스 java 스타터 프로젝트를 사용하면 훨씬 더 쉽고 편리합니다. https://code.google.com/p/google-plus-java-starter/ – hannes

답변

1

던져 나쁜 요청 예외가있다.

당신의 범위 문자열을 사용하고 있습니다 :

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

이하면 URL Shortener를 (goo.gl) API가 아닌 Google+의 API에 대한 범위입니다. 대신 당신은 아마

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

문서 여기 Google+에 대한 프로파일 범위를 사용하여 시도해야합니다 : 위 https://developers.google.com/+/api/oauth

당신이 [MYID가] ID의 두 가지 유형을 참조하는 데 사용하는 것처럼, 그것은 같습니다

아래의 문구에서 myID는 Google+ 프로필 ID (내 Google+ 프로필의 URL에서 복사/붙여 넣기 또는 현재 승인 된 사용자를 나타내는 'me'문자열 사용)이어야합니다.

,210

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

그러나, CLIENT_ID를 들어, code.google.com/apis/console에서 프로젝트의 값을 사용하여야한다.

+0

감사합니다. Ryan, 귀하의 제안으로 해결하려고 시도했지만, 하지만 작동하지 않습니다 ... 내가 언급 한대로 범위를 변경했습니다. [myID]의 경우 두 가지 유형의 ID를 사용했습니다. 나는 단지 그들을 숨기고 싶다;) – hannes

+0

올바른 범위를 사용하고있어 어떤 예외가 보이고 있는가? –

+0

코멘트에 코드를 게시 할 수 없어서 아래의이 주제에 대한 새로운 답변을 추가했습니다! HttpResponseException이 발생했습니다. 그건 그렇고, . 학사 학위 논문을 작성 중이며 Google+ 프로필 데이터를 가져 와서 내보내야합니다. 이것이 올바른 방법입니까? – hannes

관련 문제