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

gce*_*mza 5 java android android-c2dm oauth-2.0

我正在开发必须向设备发送消息的系统的服务器部分.这适用于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);

        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
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

gce*_*mza 2

由于 C2DM 目前处于 Beta 状态,因此使用 OAuth2.0 使其工作的唯一方法是创建 Web 应用程序客户端 ID,而不是服务帐户(在 Google API 控制台中)。

我已按照http://michsan.web.id/content/how-code-android-c2dm-oauth-2中的步骤进行操作,效果非常好