Bir cihaza mesaj göndermesi gereken bir sistemin sunucu bölümünü geliştiriyorum. Bu, GoogleLogin yöntemiyle sorunsuz çalışıyordu, ancak diğer kimlik doğrulama yöntemi kullanımdan kaldırıldığından OAuth 2.0'a taşımak istiyorum.OAuth2 ile doğrulanmış bir sunucudan C2DM kullanarak bir cihaza nasıl mesaj gönderebilirim?
Google API konsolunda bir proje oluşturdum ve ardından bir hizmet hesabı için bir anahtar oluşturdum. Bunu yürütmek zaman çağrılan onTokenResponse
yöntem
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("[email protected]")
.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;
}
ve ben 3600 saniyede süresi dolan token_type
"Hamiline" ile bir access_token
olsun:
Bu
ben sunucu kimlik doğrulaması için kullanıyorum kodudur. Çok uzak çok iyi.Bu, iletiyi aygıta göndermek için kullandığım koddur ve bu bana her zaman bir 401 durumu (yetkili değil) veriyor. Herhangi bir fikir?
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
}
}
Teşekkürler!