使用oauth 2向c2dm发送消息并获取401

时间:2012-05-27 18:50:51

标签: java android android-c2dm

我有一个版本的我的应用程序使用谷歌的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;

}

1 个答案:

答案 0 :(得分:0)

C2DM不支持OAuth2身份验证。 ClientLogin AuthToken是您目前唯一支持的方法。