小编gce*_*mza的帖子

如何从已使用OAuth2进行身份验证的服务器使用C2DM向设备发送消息?

我正在开发必须向设备发送消息的系统的服务器部分.这适用于GoogleLogin方法,但我想将其迁移到OAuth 2.0,因为其他身份验证方法已被弃用.

在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("something@developer.gserviceaccount.com")
                .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;
}
Run Code Online (Sandbox Code Playgroud)

当我执行此,该方法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); …
Run Code Online (Sandbox Code Playgroud)

java android android-c2dm oauth-2.0

5
推荐指数
1
解决办法
284
查看次数

标签 统计

android ×1

android-c2dm ×1

java ×1

oauth-2.0 ×1