2012-05-18 51 views
5

我正在開發必須將消息發送到設備的系統的服務器部分。這對GoogleLogin方法工作正常,但我想將其遷移到OAuth 2.0,因爲其他身份驗證方法已被棄用。如何從使用OAuth2進行身份驗證的服務器向使用C2DM的設備發送消息?

在Google API控制檯中,我創建了一個項目,然後爲服務帳戶創建了一個密鑰。

這是我使用的認證服務器的代碼:

public boolean authenticateServer(){ 
    try { 
     File privateKey = 
      new File(getClass().getResource("/something-privatekey.p12").toURI()); 

     GoogleCredential cred = 
      new GoogleCredential.Builder().setTransport(new NetHttpTransport()) 
       .setJsonFactory(new JacksonFactory()) 
       .setServiceAccountId("[email protected]") 
       .setServiceAccountScopes("https://android.apis.google.com/c2dm") 
       .setServiceAccountPrivateKeyFromP12File(privateKey) 
       .addRefreshListener(this) 
       .build(); 

     boolean success = cred.refreshToken(); 
     this.credential = cred; 
     return success;   
    } 
    catch (Exception ex) { 
     //handle this 
    } 
    return false; 
} 

當我執行此,onTokenResponse被調用的方法,我也得到一個access_tokentoken_type「承載」在3600秒到期。到現在爲止還挺好。

這是我用來發送消息到設備,它總是給我401狀態(未經授權)的代碼。有任何想法嗎?

private static String UTF8 = "UTF-8"; 
public void sendMessage(String text, String registrationId) { 
    try { 
     StringBuilder postDataBuilder = new StringBuilder(); 
     postDataBuilder 
      .append("registration_id") 
      .append("=") 
      .append(registrationId); 

     postDataBuilder.append("&") 
      .append("collapse_key") 
      .append("=") 
      .append("0"); 

     postDataBuilder.append("&") 
      .append("data.payload") 
      .append("=") 
      .append(URLEncoder.encode(text, UTF8)); 

     byte[] postData = postDataBuilder.toString().getBytes(UTF8); 

     URL url = new URL("https://android.apis.google.com/c2dm/send"); 

     HostnameVerifier hVerifier = new HostnameVerifier() { 
      public boolean verify(String hostname, SSLSession session) { 
       return true; 
      } 
     }; 

     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
     conn.setHostnameVerifier(hVerifier); 
     conn.setDoOutput(true); 
     conn.setUseCaches(false); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty(
      "Content-Type", "application/x-www-form-urlencoded"); 
     conn.setRequestProperty(
      "Content-Length", Integer.toString(postData.length)); 
     conn.setRequestProperty(
      "Authorization", "Bearer " + credential.getAccessToken()); 

     OutputStream out = conn.getOutputStream(); 
     out.write(postData); 
     out.close(); 
     int sw = conn.getResponseCode(); 
     System.out.println("" + sw); 
    } 
    catch (IOException ex){ 
     //handle this 
    } 
} 

謝謝!

回答

相關問題