5

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

当我执行此操作时,该方法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
    }
}

谢谢!

4

1 回答 1

2

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

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

于 2012-06-21T16:37:26.273 回答