1

我有一个使用来自谷歌的 c2dm 的应用程序版本,没有 oauth 身份验证,它工作正常。但我想迁移到 oauth 2。我在绑定发送消息时遇到问题,我不断收到未经授权的 401。我创建了一个服务帐户来获取 ClientID、电子邮件地址和私钥。我已经注册了 c2dm(两次),多次刷新了身份验证令牌,并且我在服务器和设备中都使用了相同的电子邮件。有谁知道为什么会这样?

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 回答