How to send a message to a device using C2DM from an authenticated server using OAuth2?

I am developing the server side of the system, which should send messages to the device. This works fine with the GoogleLogin method, but I want to port it to OAuth 2.0, as another authentication method is deprecated.

In the Google API console, I created a project and then created a key for the service account.

This is the code I use to authenticate the server:

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;
}

When this method is executed, the method is called onTokenResponse, and I get access_tokenwith token_type"Bearer" expiring after 3600 seconds. So far so good.

This is the code that I use to send a message to a device that always gives me 401 status (not authorized). Any ideas?

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
    }
}

Thank!

+5
1
+2

All Articles