1

oauth 認証なしで Google の c2dm を使用するバージョンのアプリがあり、正常に動作します。しかし、私は oauth 2 に移行したいと考えています。メッセージを送信する際に問題があり、401 の権限がありません。ClientID、電子メール アドレス、および秘密鍵を取得するためのサービス アカウントを作成しました。すでに c2dm にサインアップし (2 回)、認証トークンを複数回更新し、サーバーとデバイスの両方で同じ電子メールを使用しています。なぜこれが起こっているのか誰にも分かりますか?

public static String getToken() {

    JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport httpTransport = new NetHttpTransport();        

    String clientId = "****.apps.googleusercontent.com";
    String pkcs12Repo = "*****privatekey.p12";
    String scope = "https://android.apis.google.com/c2dm";      

        GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(clientId)
        .setServiceAccountPrivateKeyFromP12File(new File(pkcs12Repo))
        .setServiceAccountScopes(scope)
        .build();

        credential.refreshToken();
        String token = credential.getAccessToken();
        return token;
}

public static int sendMessage(String auth_token, String registrationId, String message) {

        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(message, "UTF-8"));

        byte[] postData = postDataBuilder.toString().getBytes("UTF-8");

        URL url = new URL("https://android.clients.google.com/c2dm/send");
        HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
        conn.setRequestProperty("Authorization", "Bearer " + auth_token);

        OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();

        int responseCode = conn.getResponseCode();
        return responseCode;

}

4

1 に答える 1

0

C2DM は OAuth2 認証をサポートしていません。ClientLogin AuthToken は、現時点でサポートされている唯一の方法です。

于 2012-05-27T22:59:08.300 に答える